第一個
複製代碼 代碼如下:System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
excelApp = null;
wbclass = null;
sheets = null;
worksheet = null;
range = null;
GC.Collect();
GC.WaitForPendingFinalizers();
釋放不徹底,還是有進程存在。
第二種
複製代碼 代碼如下://調用底層函數擷取進程標示
[DllImport("User32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);
private static void KillExcel(Microsoft.Office.Interop.Excel.Application theApp)
{
int id = 0;
IntPtr intptr = new IntPtr(theApp.Hwnd);
System.Diagnostics.Process p = null;
try
{
GetWindowThreadProcessId(intptr, out id);
p = System.Diagnostics.Process.GetProcessById(id);
if (p != null)
{
p.Kill();
p.Dispose();
}
}
catch (Exception ex)
{
}
}
這個方法比較好,我試過了可以關閉掉進程。