How export and no replace datagridview's data to excel?
Hello,
I am using this code for export to excel using c#:-
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"];
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "UUSSolidwoods";
// storing header part in Excel
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
//storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
// save the application
workbook.SaveAs("c:\\UUSSolidwoods.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, false, false, null, null, null);
// Exit from the application
app.Quit();
MessageBox.Show("Exported Successfully on c:\\UUSSolidwoods.xls");
I have a problem with this code:-
When we click on the export i can export and replace, but i can't cancel and no, it comes up with an exception message but no option to no and cancel,it's getting exception.
Exception from HRESULT: 0x800A03EC
Please help me.
Thanks in Advance.
Ankit Agarwal
Software Engineer