zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

c#Excel方法进程 解决 操作 利用 释放
2023-06-13 09:14:48 时间

第一个

复制代码代码如下:


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")]
   publicstaticexternintGetWindowThreadProcessId(IntPtrhWnd,outintProcessId);
   privatestaticvoidKillExcel(Microsoft.Office.Interop.Excel.ApplicationtheApp)
   {
       intid=0;
       IntPtrintptr=newIntPtr(theApp.Hwnd);
       System.Diagnostics.Processp=null;
       try
       {
           GetWindowThreadProcessId(intptr,outid);
           p=System.Diagnostics.Process.GetProcessById(id);
           if(p!=null)
           {
               p.Kill();
               p.Dispose();
           }
       }
       catch(Exceptionex)
       {

       }
   }

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