我尝试使用此方法在我的代码中获取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\...
答案 0 :(得分:0)
请尝试以下代码:
//import
using Excel = Microsoft.Office.Interop.Excel;
//define
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
private void openXL()
{
string fileName = "PATH\\FILE_NAME.xlsx"; ;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(fileName);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
答案 1 :(得分:0)
是的,可以不创建Excel的新实例。在下面使用以获取Excel应用程序的现有实例。
var path = @"C:\Temp";
var excelFileName = $@"{path}\Sample.xlsx";
var excelApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application") as Excel.Application;
// Make the object visible.
excelApp.Visible = true;
// open workbook
Excel.Workbook xlWorkbook = excelApp.Workbooks.Open(excelFileName);