【发布时间】:2019-11-29 14:28:40
【问题描述】:
我尝试使用这种方法在我的代码中获取 Excel 应用程序:
Excel.Application xlApp = GetApplication();
if (xlApp == null) xlApp = new Excel.Application();
在哪里
private Excel.Application GetApplication()
{
Excel.Application result = null;
try
{
result = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch (System.Runtime.InteropServices.COMException ex)
{
//Excel is not open
}
return result;
}
但是
System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
总是抛出异常,即使 Excel 应用程序打开。
异常:HRESULT:0x800401E3
堆栈跟踪:
in System.Runtime.InteropServices.Marshal.GetActiveObject(Guid& rclsid, IntPtr reserved, Object& ppunk)
in System.Runtime.InteropServices.Marshal.GetActiveObject(String progID)
in RaceToolTests.UnitTest1.GetApplication() in C:\Users\...
【问题讨论】:
-
您是在使用 only Interop 还是您也在使用 ClosedXML?你有没有一行
using Excel = Microsoft.Office.Interop.Excel;我在问,因为你的代码对我来说非常好。 -
我只使用互操作。在我的代码中我添加了:
using Excel = Microsoft.Office.Interop.Excel; -
您的 Excel 版本是否与 Interop 版本匹配,例如Excel 2010 是 14.0 还是 2016 是 16.0?你用的是什么版本?
-
您是否尝试过这里的解决方案 - stackoverflow.com/questions/6682678/…?你的真的很接近它。
-
这个异常仅仅意味着它找不到一个正在运行的实例。这是一个很可能的结果,问题是可能有多个正在运行的实例,而您总是非常关心您连接到哪个实例。您需要阅读讨论该行为的 KB artlcle。
标签: c# excel interop comexception