相关疑难解决方法(0)

如何正确清理Excel互操作对象?

我在C#(ApplicationClass)中使用Excel互操作,并在我的finally子句中放置了以下代码:

while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }
excelSheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Run Code Online (Sandbox Code Playgroud)

虽然这种工作,Excel.exe即使我关闭Excel后,该过程仍然在后台.只有在我的应用程序手动关闭后才会发布.

我做错了什么,或者是否有其他方法可以确保互操作对象得到妥善处理?

c# excel interop com-interop

733
推荐指数
20
解决办法
30万
查看次数

使用C#by Handle获取Excel应用程序的实例

我有一个简单的应用程序,必须在特定工作表的excel范围内写入一些值.如果不存在,我创建一个Excel应用程序的实例,但如果存在,我想设置它的活动并获取一个实例,如果它在我的代码中使用.

我使用此代码创建一个新的应用程序:

Microsoft.Office.Interop.Excel app = 
   new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
Run Code Online (Sandbox Code Playgroud)

要获取活动excel窗口的句柄,我使用此api

[DllImportAttribute("User32.dll")]
private static extern int FindWindow(String ClassName, String WindowName);
Run Code Online (Sandbox Code Playgroud)

如何通过句柄获取excel应用程序的实例?

int hWnd = FindWindow(null, "Microsoft Excel - MySheet.xlsx");
Microsoft.Office.Interop.Excel app = ....(hWnd)
Run Code Online (Sandbox Code Playgroud)

c# excel office-interop

10
推荐指数
2
解决办法
4万
查看次数

标签 统计

c# ×2

excel ×2

com-interop ×1

interop ×1

office-interop ×1