有用C#编程操作EXCEL 的朋友可能都遇到过在操作完EXCEL之后,无法关闭EXECL进程的情况。这样即浪费了内存资源,又会造成软件的不稳定性。
一般我位都是以下面方式关闭的,但很多时候都没成功/
System.Runtime.InteropServices.Marshal.ReleaseComObject(Range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
Range = null;
myBook = null;
myExcel = null;
C#和Asp.net下excel进程一被打开,有时就无法关闭, 尤其是website.对关闭该进程有过GC、release等方法,但这些方法并不是在所有情况下均适用。 于是提出了kill process的方法, 目前我见过的方法多是用进程创建时间筛选excel.exe进程, 然后kill 。 这样的方法是不精确的, 也是不安全的, 通过对网上一些关于Api运用文章的阅读, 我找到了更为直接精确找到这个process并kill的方法,以下就是代码
using System.Runtime.InteropServices;
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
protected void Button1_Click(object sender, EventArgs e)
{
Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
excel.Workbooks.Open("d:/aaa.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
IntPtr t = new IntPtr(excel.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
}