zoukankan      html  css  js  c++  java
  • c#操作excel后关闭excel.exe的方法

    1。网上的一种说法,关闭range,关闭worksheet,关闭workbook,最后关闭excel
    System.Runtime.InteropServices.Marshal.ReleaseComObject(Range); 
    2System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook); 
    3System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);

    Range = null;
    myBook = null; 
    myExcel = null;

    我试过,没有成功


    2。关闭进程
    C#和Asp.net下excel进程一被打开,有时就无法关闭,   尤其是website.对关闭该进程有过GC、release等方法,但这些方法并不是在所有情况下均适用。  于是提出了kill   process的方法,   目前我见过的方法多是用进程创建时间筛选excel.exe进程,   然后kill 。     这样的方法是不精确的,   也是不安全的,   通过对网上一些关于Api运用文章的阅读,   我找到了更为直接精确找到这个process并kill的方法,以下就是代码         
    using   System.Runtime.InteropServices;   
          
      [DllImport("User32.dll",   CharSet   =   CharSet.Auto)]   
      public   static   extern   int   GetWindowThreadProcessId(IntPtr   hwnd,   out   int   ID);   
      protected   void   Button1_Click(object   sender,   EventArgs   e)   
      {   
          Excel.ApplicationClass   excel   =   new   Microsoft.Office.Interop.Excel.ApplicationClass();   
          excel.Workbooks.Open("d:\aaa.xls",   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing);   
          IntPtr   t   =   new   IntPtr(excel.Hwnd);   
          int   k   =   0;   
          GetWindowThreadProcessId(t,   out   k);   
          System.Diagnostics.Process   p   =   System.Diagnostics.Process.GetProcessById(k);   
          p.Kill();                   
       }


    以上代码百分百成功的关闭excel.exe进程
    我的做法是结合两者,先释放资源,然后关闭进程。
    同时网上说避免使用GC.Collect 方法 (),因为会导致整个clr进行gc,影响你的性能.所以我也没有调用GC.Collect

  • 相关阅读:
    Qt 最简单的多线程方法QtConcurrent::run()
    Qt 串口收发数据
    QString使用split按照某字符进行分解
    QT新建QWidget提示框(包含设置QLabel文字大小和居中)
    Mac电脑Docker拉取Mysql报错 no matching manifest for linux/arm64/v8 in the manifest list entries
    Goframe因为axios的header导致的一个BUG解析
    PHP版本如何写出让人很难理解的代码,显得自己很有水平
    vue通用配置异步加载同时保证同步
    GO性能分析pprof
    GO runtime的用法
  • 原文地址:https://www.cnblogs.com/top5/p/1685506.html
Copyright © 2011-2022 走看看