I am exporting multiple datatable as different worksheets to a single excel file and it is working fine. However, the excel file is saved to the path specified. I want a save as dialog from where the user can select the path to save the file. I have tried the following code on button click:
protected void excelexport(object sender, EventArgs e)
{
try
{
string sql = null;
string data = null;
string path = "C:\\inetpub/wwwroot/MahindraEarth/exportexcel/exportexcel";
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
xlApp = new Excel.ApplicationClass();
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataTable dts = new System.Data.DataTable(); ;
System.Data.DataTable dss = new System.Data.DataTable();
Enquiry gs = new Enquiry();
ResultClass objres = gs.fn_GetEnquiryList();
if (objres.bStatus)
{
eslist<Enquiry> OBJLIST = objres.objData as eslist<Enquiry>;
if (OBJLIST.Count > 0)
{
dt = (DataTable)OBJLIST;
}
}
Operator op = new Operator();
ResultClass objrest = op.fn_GetOperatorList();
if (objrest.bStatus)
{
eslist<Operator> OBJLISTS = objrest.objData as eslist<Operator>;
if (OBJLISTS.Count > 0)
{
dts = (DataTable)OBJLISTS;
}
}
Contact co = new Contact();
ResultClass objress = co.fn_GetContactList();
if (objress.bStatus)
{
eslist<Contact> OBJLISS = objress.objData as eslist<Contact>;
if (OBJLISS.Count > 0)
{
dss = (DataTable)OBJLISS;
}
}
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dt);
dataSet.Tables.Add(dts);
dataSet.Tables.Add(dss);
SaveFileDialog saveFileDialog = new SaveFileDialog();
String[] Worksheets = new String[dataSet.Tables.Count];
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[dataSet.Tables.Count];
for (int k = 0; k < dataSet.Tables.Count; k++)
{
DataTable dst = dataSet.Tables[k];
xlWorkSheet[k] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(k + 1);
for (i = 0; i <= dst.Rows.Count - 1; i++)
{
for (j = 0; j <= dst.Columns.Count - 1; j++)
{
xlWorkSheet[k].Cells[1, j + 1] = dataSet.Tables[k].Columns[j].ColumnName;
data = dst.Rows[i].ItemArray[j].ToString();
xlWorkSheet[k].Cells[i + 2, j + 1] = data;
xlWorkSheet[k].Name = dataSet.Tables[k].TableName;
}
}
}
xlWorkBook.SaveAs(path + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
for (int p = 0; p < 3; p++)
{
releaseObject(xlWorkSheet[p]);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
exportsuccess.Style.Add("display", "");
}
catch (Exception ex)
{
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
How to get the save as dialog box in order to save the multiple datatables in multiple worksheet and not as a single sheet.
Thanks,
give this a try. This should give you the Save As dialog box. Some of the code should look similar to yours, which should give you an idea as to where this code excerpt should be attached.
#region Save & Quit
//Save and quit, use SaveCopyAs since SaveAs does not always work
Guid id = Guid.NewGuid();
string uniqueFileName = id.ToString() + ".xls";
string fileName = Server.MapPath("~/" + uniqueFileName);
xlApp.DisplayAlerts = false; //Supress overwrite request
xlWorkBook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
//Release objects
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
//Give the user the option to save the copy of the file anywhere they desire
String FilePath = Server.MapPath("~/" + uniqueFileName);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=MyClaimsReport-" + DateTime.Now.ToShortDateString() + ".xls;");
response.TransmitFile(FilePath);
response.Flush();
response.Close();
//Delete the temporary file
DeleteFile(fileName);
#endregion
private void DeleteFile(string fileName)
{
if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
}
catch (Exception ex)
{
//Could not delete the file, wait and try again
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(fileName);
}
catch
{
//Could not delete the file still
}
}
}
}
Related
I am trying to save the data table values into excel. I have a Load Report button from which I am getting data into a grid view.
Load Report Button Code
private void BtnInvHD_Click(object sender, EventArgs e)
{
string dir = #"C:\Output\Log\HavingDuesLog";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string location = Path.Combine(dir, "HavingDues_log_"+name+"_" + DateTime.Now.ToString("dd-MM-yy_hh:mm:ss") + ".xls");
string cs = LoginForm.cs;
date = dtPicker.Value.ToString("yyyy-MM-dd");
if (cnn.State == ConnectionState.Closed)
{
cnn.Open();
}
sqlCmd = new SqlCommand("RptIV030", cnn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#DateFrom", date);
SqlDataAdapter sqlSda = new SqlDataAdapter(sqlCmd);
sqlSda.Fill(dtData);
dGInvHD.DataSource = dtData;
writeExcelFile(location,dtData);
btnExport.Enabled = true;
//return dtData;
}
Write to Excel Function
public void writeExcelFile(string location, DataTable read)
{
//Create excel app object
Microsoft.Office.Interop.Excel.Application xlSamp = new Microsoft.Office.Interop.Excel.Application();
if (xlSamp == null)
{
MessageBox.Show("Excel is Not Installed");
//Console.WriteLine("Excel is not Insatalled");
//Console.ReadKey();
return;
}
//Create a new excel book and sheet
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlSamp.Workbooks.Add(misValue);
// get the reference of first sheet.
// store its reference to worksheet
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet = xlWorkBook.ActiveSheet;
// changing the name of active sheet
xlWorkSheet.Name = "Having Dues-" + name + "-Till-" + date;
// column headings
for (var i = 0; i < read.Columns.Count; i++)
{
xlWorkSheet.Cells[1, i + 1] = read.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < read.Rows.Count; i++)
{
// to do: format datetime values before printing
for (var j = 0; j < read.Columns.Count; j++)
{
xlWorkSheet.Cells[i + 2, j + 1] = read.Rows[i][j];
}
}
//Save the opened excel book to custom location
//Dont forget, you have to add to exist location
xlWorkBook.SaveAs(location, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlSamp.Quit();
//release Excel Object
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSamp);
xlSamp = null;
}
catch (Exception ex)
{
xlSamp = null;
MessageBox.Show(ex.ToString());
}
finally
{
GC.Collect();
}
}
When I execute my code am I able to view data into gridview but unable to write it into an excel file.
I am getting error at xlWorkBook.SaveAs(location, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
Error Message
The file could not be accessed. Try one of the following:
Make sure the specified folder exists.
Make sure the folder that contains the file is not read-only.
Make sure the filename and folder path do not contain any of the following characters: < > ? [ ] : | or *
Make sure the filename and folder path do not contain more than 218 characters.
Any help would be highly appreciated.
Use something Like this I think its useful:
xlSamp.ActiveWorkbook.SaveAs(filepath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xlSamp.ActiveWorkbook.Close(true, missing, missing);
xlSamp.Quit();
Make sure the filename and folder path do not contain more than 218 characters.
This error comes when your location path will be to long reduce path
Make sure the specified folder exists.
Make sure the folder that contains the file is not read-only.
Make sure your location folder must exists on that location and give
read write permission to that folder
Make sure the filename and folder path do not contain any of the following characters: < > ? [ ] : | or *
give folder name and filename proper format
I am trying to put different data into different worksheet in the same Workbook, and each worksheet have different page setup(like header,footer,etc).
When I execute the program, the data can be successfully displayed in different worksheet, but the page setup is not working (like header and footer is missing) when I checking print preview, does anyone know the reason?
bellow is the button click event:
private void btnExportAllToExcel_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "StockReport(ALL)_" + DateTime.Now.ToString("ddMMyyyy HHmmss") + ".xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
Cursor = Cursors.WaitCursor; // change cursor to hourglass type
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.PrintCommunication = false;
xlexcel.ScreenUpdating = false;
xlexcel.DisplayAlerts = false; // Without this you will get two confirm overwrite prompts
Workbook xlWorkBook = xlexcel.Workbooks.Add(misValue);
saveDataToSheet(xlWorkBook);
xlexcel.Calculation = XlCalculation.xlCalculationManual;
//Save the excel file under the captured location from the SaveFileDialog
xlWorkBook.SaveAs(sfd.FileName, XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlexcel.DisplayAlerts = true;
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlWorkBook);
releaseObject(xlexcel);
// Clear Clipboard and DataGridView selection
Clipboard.Clear();
dgvStockReport.ClearSelection();
// Open the newly saved excel file
if (File.Exists(sfd.FileName))
System.Diagnostics.Process.Start(sfd.FileName);
}
}
bellow is the code for copy data from datagridview to sheet method, and I think the problem will be here but I cannot find it:
//copy data from datagridview to clipboard and paste to excel sheet
private void saveDataToSheet(Workbook xlWorkBook)
{
int sheetNo = 1;
Worksheet xlWorkSheet = null;
bool gotData = false;
//load different data list to datagridview by changing the comboBox selected index
for (int i = 0; i <= cmbType.Items.Count - 1; i++)
{
cmbType.SelectedIndex = i;
for (int j = 0; j <= cmbSubType.Items.Count - 1; j++)
{
cmbSubType.SelectedIndex = j;
if (cmbType.Text.Equals(CMBPartHeader))
{
gotData = loadPartStockData();//if data != empty return true, else false
}
else if (cmbType.Text.Equals(CMBMaterialHeader))
{
gotData = loadMaterialStockData();//if data != empty return true, else false
}
if(gotData)//if datagridview have data
{
copyAlltoClipboard();//select all from datagridview and copy to clipboard
//create new sheet
var xlSheets = xlWorkBook.Sheets as Sheets;
var xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[sheetNo], Type.Missing, Type.Missing, Type.Missing);
xlWorkSheet = xlNewSheet;
xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(sheetNo);
xlWorkSheet.Name = cmbSubType.Text;
//Header and Footer setup
xlWorkSheet.PageSetup.LeftHeader = "&\"Calibri,Bold\"&11 " + DateTime.Now.Date.ToString("dd/MM/yyyy"); ;
xlWorkSheet.PageSetup.CenterHeader = "&\"Calibri,Bold\"&16 (" + cmbSubType.Text + ") Stock List";
xlWorkSheet.PageSetup.RightHeader = "&\"Calibri,Bold\"&11 PG -&P";
xlWorkSheet.PageSetup.CenterFooter = "Printed By " + dalUser.getUsername(MainDashboard.USER_ID);
//Page setup
xlWorkSheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4;
xlWorkSheet.PageSetup.Orientation = XlPageOrientation.xlPortrait;
xlWorkSheet.PageSetup.Zoom = false;
xlWorkSheet.PageSetup.CenterHorizontally = true;
xlWorkSheet.PageSetup.LeftMargin = 1;
xlWorkSheet.PageSetup.RightMargin = 1;
xlWorkSheet.PageSetup.FitToPagesWide = 1;
xlWorkSheet.PageSetup.FitToPagesTall = false;
xlWorkSheet.PageSetup.PrintTitleRows = "$1:$1";
// Paste clipboard results to worksheet range
xlWorkSheet.Select();
Range CR = (Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
//content edit
Range tRange = xlWorkSheet.UsedRange;
tRange.Borders.LineStyle = XlLineStyle.xlContinuous;
tRange.Borders.Weight = XlBorderWeight.xlThin;
tRange.Font.Size = 11;
tRange.EntireColumn.AutoFit();
tRange.Rows[1].interior.color = Color.FromArgb(237, 237, 237);//change first row back color to light grey
sheetNo++;
// Clear Clipboard and DataGridView selection
Clipboard.Clear();
dgvStockReport.ClearSelection();
releaseObject(xlWorkSheet);
}
}
}
}
I'm new here and coding as well, so if I'm doing anything wrong please let me know , thank you very much ^^
After online research and modify my code about 4 hours, now it's work!
I try to save the workbook first,
then open it for insert data to worksheet and changing the page setup.
CODE:
private void btnExportAllToExcel_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "StockReport(ALL)_" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = Path.GetFullPath(sfd.FileName);
Cursor = Cursors.WaitCursor; // change cursor to hourglass type
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.PrintCommunication = false;
xlexcel.ScreenUpdating = false;
xlexcel.DisplayAlerts = false; // Without this you will get two confirm overwrite prompts
Workbook xlWorkBook = xlexcel.Workbooks.Add(misValue);
//Save the excel file under the captured location from the SaveFileDialog
xlWorkBook.SaveAs(sfd.FileName,
XlFileFormat.xlWorkbookNormal,
misValue, misValue, misValue, misValue,
XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
insertDataToSheet(path,sfd.FileName);
xlexcel.DisplayAlerts = true;
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlWorkBook);
releaseObject(xlexcel);
// Clear Clipboard and DataGridView selection
Clipboard.Clear();
dgvStockReport.ClearSelection();
}
}
here is the code for insert data to worksheet method:
private void insertDataToSheet(string path, string fileName)
{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = true;
Workbook g_Workbook = excelApp.Workbooks.Open(
path,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
bool gotData = false;
object misValue = System.Reflection.Missing.Value;
//load different data list to datagridview but changing the comboBox selected index
for (int i = 0; i <= cmbType.Items.Count - 1; i++)
{
cmbType.SelectedIndex = i;
for (int j = 0; j <= cmbSubType.Items.Count - 1; j++)
{
cmbSubType.SelectedIndex = j;
if (cmbType.Text.Equals(CMBPartHeader))
{
gotData = loadPartStockData();//if data != empty return true, else false
}
else if (cmbType.Text.Equals(CMBMaterialHeader))
{
gotData = loadMaterialStockData();//if data != empty return true, else false
}
if (gotData)//if datagridview have data
{
Worksheet addedSheet = null;
int count = g_Workbook.Worksheets.Count;
addedSheet = g_Workbook.Worksheets.Add(Type.Missing,
g_Workbook.Worksheets[count], Type.Missing, Type.Missing);
addedSheet.Name = cmbSubType.Text;
addedSheet.PageSetup.LeftHeader = "&\"Calibri,Bold\"&11 " + DateTime.Now.Date.ToString("dd/MM/yyyy"); ;
addedSheet.PageSetup.CenterHeader = "&\"Calibri,Bold\"&16 (" + cmbSubType.Text + ") STOCK LIST";
addedSheet.PageSetup.RightHeader = "&\"Calibri,Bold\"&11 PG -&P";
addedSheet.PageSetup.CenterFooter = "Printed By " + dalUser.getUsername(MainDashboard.USER_ID);
//Page setup
addedSheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4;
addedSheet.PageSetup.Orientation = XlPageOrientation.xlPortrait;
addedSheet.PageSetup.Zoom = false;
addedSheet.PageSetup.CenterHorizontally = true;
addedSheet.PageSetup.LeftMargin = 1;
addedSheet.PageSetup.RightMargin = 1;
addedSheet.PageSetup.FitToPagesWide = 1;
addedSheet.PageSetup.FitToPagesTall = false;
addedSheet.PageSetup.PrintTitleRows = "$1:$1";
copyAlltoClipboard();
addedSheet.Select();
Range CR = (Range)addedSheet.Cells[1, 1];
CR.Select();
addedSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
Range tRange = addedSheet.UsedRange;
tRange.Borders.LineStyle = XlLineStyle.xlContinuous;
tRange.Borders.Weight = XlBorderWeight.xlThin;
tRange.Font.Size = 11;
tRange.EntireColumn.AutoFit();
tRange.Rows[1].interior.color = Color.FromArgb(237, 237, 237);//change first row back color to light grey
Clipboard.Clear();
dgvStockReport.ClearSelection();
}
}
}
g_Workbook.Worksheets.Item[1].Delete();
g_Workbook.Save();
}
I have wrote the following code for exporting my local database data to an excel file. The fact is that it is working properly, but I'd only like to export it with the actual date, or just month, like august, or something like that. Besides that, the problem that really matters is that it replaces every time the previously exported excel file. How can I change this thing? Thanks !
private void button3_Click_1(object sender, EventArgs e)
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM info ";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
//adds column names to excel
string[] colNames = new string[dataGridView1.Columns.Count];
int col = 0;
foreach (DataGridViewColumn dc in dataGridView1.Columns)
colNames[col++] = dc.HeaderText;
char lastColumn = (char)(65 + dataGridView1.Columns.Count - 1);
xlWorkSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
xlWorkSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
xlWorkSheet.get_Range("A1", lastColumn + "1").VerticalAlignment
= Excel.XlVAlign.xlVAlignCenter;
xlWorkBook.SaveAs(#"C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\db.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Salvat cu succes");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
If you don't want it to overwrite the same workbook every time then you'll need to specify a different file name rather than hard coding it in.
Something simple like creating the filename with the current datetime would normally be sufficient (you can change the format to suit you):
string fileName = #"db " + DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss") + #".xls";
string filePath = Path.Combine(#"C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag", fileName);
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
This would produce a file like this:
db 01-09-2015 10-32-35.xls
There is still not explicit check to see if the file exists, but unless you're clicking it every second it's unlikely to overwrite.
My small console tool tries to read an excel file and create new out of that depending on set criteria.
Problem: When there is a filename conflict(file already exists with same name), programme should generate the file with an unique name. But now a message comes up with "yes/no/cancel" message box to save the file. If user clicks NO then exception thrown. The message is as follows:
A file named 'D:\sample.xls' already exists in this location. Do you want to replace it?
The exception:
A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in ExcelSplitter.exe
Additional information: Exception from HRESULT: 0x800A03EC
The following line thorws the exception
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
The code is as follows:
private bool WriteToExcel(String fileName, List<RowEntity> headerRowObj, List<RowEntity> dataRowObj)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int headerRowTotal = 0;
for (int i = 0; i < headerRowObj.Count; i++)
{
for (int j = 0; j < headerRowObj[i].ColumnValues.Count; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = headerRowObj[i].ColumnValues[j].ToString();
}
headerRowTotal++;
}
for (int i = 0; i < dataRowObj.Count; i++)
{
for (int j = 0; j < dataRowObj[i].ColumnValues.Count; j++)
{
xlWorkSheet.Cells[headerRowTotal + i + 1, j + 1] = dataRowObj[i].ColumnValues[j].ToString();
}
}
if (IsExcelFileOpen(xlWorkBook))
{
errorList.Add(Error.GetError(-7));
return false;
}
else
{
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
ReleaseObject(xlWorkSheet);
ReleaseObject(xlWorkBook);
ReleaseObject(xlApp);
return true;
}
The above method is called in the following method:
private int SeparateExcleFiles(int headerLines, int groupOnColumn, string outputPath, string inputFile, FileEntity fileObj, RowEntity rowObj)
{
List<RowEntity> headerRowObj = fileObj.RowValues.GetRange(0, headerLines);
if (rowObj.ColumnValues.Count < groupOnColumn)
{
errorList.Add(Error.GetError(-6));
return -6;
}
else
{
var dataRows = fileObj.RowValues.GetRange(headerLines, fileObj.RowValues.Count - (headerLines)).GroupBy(re => re.ColumnValues[groupOnColumn - 1]).ToList();
for (int i = 0; i < dataRows.Count; i++)
{
var fileName = String.Format("{0}-{1}{2}", Path.GetFileNameWithoutExtension(inputFile), dataRows[i].Key.ToString(), Path.GetExtension(inputFile));
var filePath = Path.Combine(outputPath, fileName);
if (File.Exists(filePath))
{
fileName = GetUniqueFilename(fileName);
}
if (WriteToExcel(filePath, headerRowObj, dataRows[i].ToList() as List<RowEntity>))
{
System.Console.WriteLine("Wrote {0}", fileName);
}
}
return 0;
}
}
private bool IsExcelFileOpen(Workbook wBook)
{
Excel.Application exApp;
exApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
try
{
exApp.Workbooks.get_Item(wBook);
return true;
}
catch (Exception)
{
return false;
}
}
Where exactly am I doing it wrong?
Could you try this on the saveas part.
try
{
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
}
catch(Exception e)
{
//BLANK (do nothing)
}
This will allow you to handle the exception, but if you don't want to do anything and just not overwrite just leave the handling process blank.
Having the exception handler will let the system think that you acknowledged the event and will let the program continue.
I looked a lots of example and demo but I could not to it.
I'm trying to convert datagridview to excel.
My Results
http://i.imgur.com/ujvGiXX.png
But its convert to excel like this
http://i.imgur.com/0OXkUkL.png
I want to copy cells size and color but how?
I convert to excel with this code
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = listBox1.SelectedItem.ToString() + " " + listBox3.SelectedItem.ToString() + " Stok Reçeteleri" + ".xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
//ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name
xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
//xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.X
FileInfo fileInfo = new FileInfo(sfd.FileName);
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
update the internal loop to be:
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
Range range = (Range)xlWorkSheet.Cells[i + 1, j + 1];
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
range.Interior.Color = System.Drawing.ColorTranslator.ToOle(dataGridView1.Rows[i].DefaultCellStyle.BackColor );
}
}
don't forget:
using Microsoft.Office.Interop.Excel;
see: Change the background of Cells with C#
Try this code for exporting to excel instead of what you are using. I use this for web apps though.
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "SomeFileName" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}