加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#利用com操作excel释放进程的解决方法

发布时间:2020-12-15 05:50:12 所属栏目:百科 来源:网络整理
导读:第一个 复制代码 代码如下: System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets); System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); System.Runtim

第一个

复制代码 代码如下:

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

        }
    }

这个方法比较好,我试过了可以关闭掉进程。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读