[英]com exception excel InteropServices.COMException - c#
I am receiving System.Runtime.InteropServices.COMException
when running the below method from main()
从main()
运行以下方法时,我收到System.Runtime.InteropServices.COMException
I want to get true
and later access the sheet if excel is opened on system.如果 excel 在系统上打开,我想得到true
的稍后访问工作表。 I am making sure excel is opened and sheet1
is there but I get false
and the error above.我确保 excel 已打开并且sheet1
在那里,但我得到false
并且上面的错误。
using Excel = Microsoft.Office.Interop.Excel;
public static bool IsExcelOpened(string sheet1)
{
bool isOpened = true;
Excel.Application exApp;
exApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
try
{
Excel.Worksheet xlWorksheet;
xlWorksheet = (Excel.Worksheet)exApp.Workbooks.get_Item(sheet1);
}
catch (Exception)
{
isOpened = false;
}
return isOpened;
}
EDIT: when I run VS2019 as admin, I received more infor on error编辑:当我以管理员身份运行 VS2019 时,我收到了更多关于错误的信息
Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))
I think your issue is Visual Studio running in a different context to Excel. 我认为您的问题是Visual Studio在与Excel 不同的上下文中运行。
I tried a slightly modified version of your code and it works just fine when running Visual Studio NOT as admin (same user as excel was opened with). 我想你的代码稍加修改的版本,并在运行Visual Studio 不是管理员(同一用户的Excel与开),当它工作得很好。
Might be worth checking you are using the right version of the interop dll also. 可能值得检查您是否也在使用正确版本的interop dll。
public bool IsExcelOpened()
{
bool isOpened = false;
try
{
Excel.Application exApp;
Excel.Worksheet xlWorksheet;
exApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application") as Excel.Application;
if(exApp != null)
{
xlWorksheet = (Excel.Worksheet)exApp.ActiveSheet;
isOpened = true;
}
}
catch { }
return isOpened;
}
I also was facing the same issue, the main reason is Microsoft doesn't support the Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services).我也遇到了同样的问题,主要原因是微软不支持任何无人值守、非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT 服务)的 Microsoft Office 应用程序自动化。 So, I tried to manually register the excel to ROT (running object table) by using a shell command like Process.Start("Path to your excel file")
before creating the Marshal.GetActiveObject()
. So, I tried to manually register the excel to ROT (running object table) by using a shell command like Process.Start("Path to your excel file")
before creating the Marshal.GetActiveObject()
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.