I have requirement to dump from SQL DB to excel file.There is only one database in SQL and query output in data grid view needs to be dumped in excel sheet.
I have written the following code and used <pre>Microsoft.Office.Interop.Excel.Application Excel
.
After all the contents of DataGridView successfully dumped to excel sheet, I am getting the error attached in the screenshot video.Attaching the portion of code responsible for dump as follows.
I am new to C# and not able to troubleshoot the issue since long.
The code used to dump datagridview to excel is as follwos.
-------------------------------------------------------------------------------
using Microsoft.Office.Interop.Excel;
private void button2_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)Excel.ActiveSheet;
Excel.Visible = true;
ws.Cells[1, 1] = "Name of place";
ws.Cells[1, 2] = "Element Name";
ws.Cells[1, 3] = "No";
ws.Cells[1, 4] = "Make Name";
ws.Cells[1, 5] = "Model name";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
ws.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
ws.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
int rowCount = ((System.Data.DataTable)this.dataGridView1.DataSource).Rows.Count;
MessageBox.Show("You have exported " + rowCount.ToString() + " rows.Please close this excel before creating a new one.");
Excel.Quit();
}
-----------------------------------------------------------------------------------
It gives,
----------------------------------------------------
COMException occurred.
At first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll. Additional information: Exception from HRESULT:0x800A03EC
-------------------------------------------
Troubleshooting tips:
Check the Error Code property pf the exception to determine the HRESULT returned by the COM object.
-------------------------------------------------------------------------
Also in task manage multiple instances of EXCEL.exe is running.
Can somebody help me out to troubleshoot the issue?
What I have tried:
Tried a from different code project forum and stack overflow. There is a lot of post regarding this.But it did not work for me.I am new to C# too.