解析c#操作excel后关闭excel.exe的方法

时间:2021-08-14 16:55:22 

于是提出了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

标签:c#,excel,excel.exe
0
投稿

猜你喜欢

  • 理解zookeeper选举机制

    2023-04-15 20:09:44
  • 一个Servlet是如何处理多个请求的?

    2023-01-18 11:19:32
  • Java编程实现统计一个字符串中各个字符出现次数的方法

    2023-01-24 18:02:20
  • 详解springboot项目带Tomcat和不带Tomcat的两种打包方式

    2023-11-28 08:23:41
  • Java 获取两个List的交集和差集,以及应用场景操作

    2021-11-21 17:49:43
  • mybatis注解与xml常用语句汇总

    2022-05-17 18:39:47
  • Java守护线程实例详解_动力节点Java学院整理

    2023-03-29 08:14:30
  • Spring整合Quartz实现动态定时器的示例代码

    2022-10-22 06:48:17
  • Spring定时任务中@PostConstruct被多次执行异常的分析与解决

    2022-08-20 07:28:22
  • Unity 从Resources中动态加载Sprite图片的操作

    2023-08-26 11:37:18
  • Spring Cloud Eureka(全面解析) 大白话

    2022-11-12 22:43:02
  • Spring maven filtering使用方法详解

    2021-07-02 22:14:46
  • C# 装箱和拆箱的知识回顾

    2022-07-19 09:27:58
  • android线程消息机制之Handler详解

    2023-07-28 11:31:52
  • OPENCV+JAVA实现人脸识别

    2022-03-15 18:31:39
  • springboot log4j2日志框架整合与使用过程解析

    2021-09-12 00:13:28
  • JAVA 实现磁盘文件加解密操作的示例代码

    2023-11-15 00:13:06
  • thymeleaf中前后端数据交互方法汇总

    2023-07-18 21:15:59
  • Android Service详解及示例代码

    2021-12-24 05:44:17
  • Java开发实现猜拳游戏

    2023-09-27 03:21:46
  • asp之家 软件编程 m.aspxhome.com