Using can open excel workbook with console app but not with a windows forms app


I have been able to open an excel workbook using a console app in Visual Studio 2019 with the following code:

 using Excel = Microsoft.Office.Interop.Excel;
 private void OpenXL2()
        Excel.Application excelApp = new Excel.Application();
        if (excelApp == null)

        // open an existing workbook

        string workbookPath = @"C:\Illustrator\InvoiceTemplates\invtemplate.xls";
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath);

        excelApp.Visible = true;

        // get all sheets in workbook
        Excel.Sheets excelSheets = excelWorkbook.Worksheets;

        // get some sheet
        string currentSheet = "TimeSheet";
        Excel.Worksheet excelWorksheet =


but when I try to use the same code in a windows form app the following error occurs when the excelApp.Workbooks.Open(workbookPath) is reached:

System.InvalidCastException: 'Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type '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: Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).'

I have added a reference to the "Microsoft Excel 16.0 Object Library"


asked on Stack Overflow Nov 15, 2020 by philb39956 • edited Nov 15, 2020 by stuartd

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0