使用Microsoft.Office.Interop.Excel创建Excel文件突然报错
问题:Office Interop Excel 类型转换失败报错
我有一个运行了15年的项目,最近在本地和用户办公电脑上创建Excel文件时突然报错。为排查问题,我在Windows 10下新建了基于.NET Framework 4.7.2的Windows Forms项目,安装Microsoft.Office.Interop.Excel NuGet包后,在窗体按钮点击事件中编写设置单元格值为"Hello World"的代码,仍出现相同报错。尝试修复Excel无效,也未在网上找到解决方案。
报错信息
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: Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND)).'
报错的VB.NET代码(Option Strict On)
Dim xlApp As Excel.Application = New Excel.Application() Dim xlWb As Excel.Workbook = xlApp.Workbooks.Add() ' 该行报错 Dim xlSheet As Excel.Worksheet = CType(xlWb.Sheets(1), Excel.Worksheet) xlSheet.Cells(1, 1).FormulaR1C1 = "hello world!" xlApp.Workbooks(1).SaveAs("testing.xls") xlApp.Visible = True
可行的VB.NET代码(关闭Option Strict,未安装NuGet包)
Dim xlApp As Object = Nothing Dim xlBook As Object Dim xlSheet As Object xlApp = CreateObject("Excel.Application") xlApp.Visible = False xlApp.DisplayAlerts = False xlBook = xlApp.Workbooks.Add xlSheet = xlBook.Sheets(1) xlSheet.Cells(1, 1).FormulaR1C1 = "Hello world!" xlApp.Visible = True
内容的提问来源于stack exchange,提问作者Tim F
相关产品推荐
相关产品推荐

