【发布时间】:2021-02-27 05:19:32
【问题描述】:
我已经能够使用 Visual Studio 2019 中的控制台应用打开一个 Excel 工作簿,代码如下:
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);
}
但是当我尝试在 Windows 窗体应用程序中使用相同的代码时,当达到 excelApp.Workbooks.Open(workbookPath) 时会出现以下错误:
System.InvalidCastException: '无法将'Microsoft.Office.Interop.Excel.ApplicationClass' 类型的 COM 对象转换为接口类型'Microsoft.Office.Interop.Excel._Application'。此操作失败,因为 IID 为“{000208D5-0000-0000-C000-000000000046}”的接口的 COM 组件上的 QueryInterface 调用因以下错误而失败:未注册类(来自 HRESULT 的异常:0x80040154 (REGDB_E_CLASSNOTREG))。 '
我添加了对“Microsoft Excel 16.0 对象库”的引用
谢谢。
【问题讨论】:
-
你真的需要在这里使用Interop吗? Interop 会打开整个 Excel 应用程序。如果您只想处理文件中的数据,那么您可以使用另一个库(有几个通过 Nuget 包提供的免费库),它会更可靠。
-
尝试在 Office 上运行快速修复 stackoverflow.com/questions/28066719/…
-
感谢您的回复。我确实修复了 excel 安装,但问题仍然存在。
-
The console app and the winforms app are created in Visual Studio 2019 and are .NET.再次阅读我的问题。 -
回复 mjwills:感谢您为我指明了正确的方向!控制台应用程序的 .NET /Core 版本是 3.1,Windows 窗体应用程序是 4.7.2。我将 Windows 窗体应用程序的 .NET 版本设置为 4.5.1,应用程序运行成功!然后我将它重置回 4.7.2 并且运行良好。
标签: c# excel visual-studio-2019