C#: some of machines are throwing following error: Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass'

1

I had created a C# function which saves DataGridView to Excel which works well on most of machines. However, some of machines are throwing following error:

Microsoft.Office.Interop.Excel._Application. This operation failed because the QueryInterface call on the COM component for the interface with IID ‘{000208D5-0000-0000-C000-000000000046}’ failed due to the following error: Library not registered. (Exception from HRESULT 0x8002801D (TYPE_E_LIBNOTREGISTERED)).

Is there any way I can fix this issue?

This is my source code:

private bool dataGridView_ExportToExcel(string fileName, DataGridView dgv, string ext, bool chart)
{
    CheckForIllegalCrossThreadCalls = false;
    Excel.Application excelApp = new Excel.Application();

    if (excelApp == null)
    {
        MessageBox.Show("No Excel has been installed!");
        return false;
    }

    Excel.Workbook wb = excelApp.Workbooks.Add(true);
    Excel._Worksheet workSheet = wb.Worksheets.get_Item(1) as Excel._Worksheet;
    workSheet.Name = "C#";

    // Print Contents
    for (int r = 0; r < dgv.Rows.Count; r++)
    {
        for (int i = 0; i < dgv.Columns.Count; i++)
        {
            workSheet.Cells[r + 2, i + 1] = dgv.Rows[r].Cells[i].Value;
        }
    }

    workSheet.Columns.AutoFit();
    wb.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlUserResolution, true, Type.Missing, Type.Missing, Type.Missing);

    wb.Close(Type.Missing, Type.Missing, Type.Missing);
    excelApp.Quit();
    releaseObject(excelApp);
    releaseObject(workSheet);
    releaseObject(wb);

    return true;
}

I am using .NET framework 4.6.1 environment.

Thank you for reading. have a nice day :)

c#
datagridview
asked on Stack Overflow Jan 10, 2021 by (unknown user)

1 Answer

1

It seems some of contents are missing from the windows registry key,

and this can be happening when MS Excel is downgraded.

To fix this issue, Please go to regedit and delete [HKEY_CLASSES_ROOT-->TypeLib-->{00020813-0000-0000-C000-000000000046} --> 1.9]

and see if this works.

Registry

answered on Stack Overflow Jan 10, 2021 by (unknown user)

User contributions licensed under CC BY-SA 3.0