[英]How to get Excel.Application instance in C#?
我尝试使用此方法在我的代码中获取 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\...
请尝试以下代码:
//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);
}
是的,可以不创建 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.