gpt4 book ai didi

c# - 如何在 C# 中获取 Excel.Application 实例?

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:47 25 4
gpt4 key购买 nike

我尝试使用此方法在我的代码中获取 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);
}

关于c# - 如何在 C# 中获取 Excel.Application 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46280653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com