我試圖讓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