程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C#利用com操作excel釋放進程的解決方法

C#利用com操作excel釋放進程的解決方法

編輯:C#基礎知識

第一個

代碼如下:

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)
        {

        }
    }

這個方法比較好,我試過了可以關閉掉進程。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved