0
votes

I am tring to export datagridview content to excel but it throws exception. I have a method

private void exportDataGridToExcel(DataGridView grd)
        {
            if (saveFileToExcel.ShowDialog() != DialogResult.Cancel)
            {
                Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();

                Workbook wb;
                Worksheet ws;

                wb = Excel.Workbooks.Add();
                ws = (Worksheet)wb.Worksheets.get_Item(1);

                for (int i = 0; i < grd.Columns.Count + 1; i++)
                {
                    ws.Cells[1, i] = grd.Columns[i - 1].HeaderText;
                }
                for (int i = 0; i <= grd.Rows.Count; i++)
                {
                    for (int j = 0; j <= grd.Columns.Count; j++)
                    {
                        ws.Cells[i + 1, j + 1] = grd.Rows[i - 1].Cells[j].Value.ToString();
                    }
                }
                wb.SaveAs(saveFileToExcel.FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);

                wb.Close(ws);
                Excel.Quit();
            }
        }

and when i click on button it calls that method like this

private void btnCheck_Click(object sender, EventArgs e)
        {
     exportDataGridToExcel(dataDaily);
        }

but it throws exception in this line of code Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application(); this exception:

"An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))."

1
I think the exception message doesn't tell much about the error, but taking a look at your code, seems there are few mistakes, grd.Columns[i - 1].HeaderText [i - 1]?? while your index starts from 0; similarly grd.Rows[i - 1]Abdulkarim Kanaan
I deleted - 1 and i throws another exception An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll Additional information: Exception from HRESULT: 0x800A03EC When this line of code is called ws.Cells[1, i] = grd.Columns[i - 1].HeaderText;Zorge
the general concept of arrays is that they are zero-indexed; having said that grd.Columns[i - 1]?! (i - 1) means index of -1, there is no index of minus valueAbdulkarim Kanaan

1 Answers

1
votes

enter image description hereMake sure you a referencing the correct interop dll for the version of excel you have installed on your computer.

In your references, you will see a version for excel. You need to make sure you have that version of excel installed on the machine loading the DLL.