简体   繁体   中英

Using c#.net 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)
        {
            return;
        }

        // 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 =
             (Excel.Worksheet)excelSheets.get_Item(currentSheet);

    }

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"

Thanks.

try like that

Type excel_type = Type.GetTypeFromProgID("Excel.Application");
        dynamic excel_obj = Activator.CreateInstance(excel_type);
        var workbook = excel_obj.Workbooks.Open(Filename: filePath, ReadOnly: false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM