一般我位都是以下面方式關閉的,但很多時候都沒成功/
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();
}