zoukankan      html  css  js  c++  java
  • C#利用com操作excel释放进程

    最近利用Microsoft.Office.Interop.Excel.Application读取一个excel后,进程中一直存在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)
            {
                
            }
        }

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

  • 相关阅读:
    測试能否发表博客
    换站点Logo图片---轻开电子商务系统(企业入门级B2C站点)
    后台运行命令:&和nohup command & 以及关闭、查看后台任务
    HttpClient将手机上的数据发送到服务器
    支付宝电脑网站支付
    远程使用tomcat8的首页的管理工具
    数据结构之链表基本操作
    数据结构之链表反向打印
    ultraedit开发使用技巧
    charles抓取https中出现unknow
  • 原文地址:https://www.cnblogs.com/x4646/p/2975844.html
Copyright © 2011-2022 走看看