当前位置: 移动技术网 > IT编程>开发语言>c# > C#利用com操作excel释放进程的解决方法

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

第一个

复制代码 代码如下:

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

        }
    }

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网