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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-18 我要评论
想了解C#利用com操作excel释放进程的解决办法的相关内容吗,在本文为您仔细讲解C#利用com操作excel释放进程的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:com,excel,下面大家一起来学习吧。

第一个

复制代码 代码如下:

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

        }
    }

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们