我试图让Excel应用程序在我的代码用这种方法:如何在C#中获取Excel.Application实例?
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_互操作或者您也使用ClosedXML吧?你有一行'使用Excel = Microsoft.Office.Interop.Excel;'我问,因为你的代码对我来说工作得很好。 – LocEngineer
我只使用Interop。在我的代码中,我添加了:'使用Excel = Microsoft.Office.Interop.Excel;' – KentuckyJack92
您的Excel版本是否与Interop版本匹配Excel 2010为14.0还是2016为16.0?你使用什么版本? – LocEngineer