展会信息港展会大全

解析c#操作excel后关闭excel.exe的方法
来源:互联网   发布日期:2016-01-26 10:18:17   浏览:1927次  

导读:C 和Asp net下excel进程一被打开,有时就无法关闭,尤其是website 对关闭该进程有过GC、release等方法,但这些方法并不是在所有情况下均适用于是提出了kill process的方法,目前我见过的方法多是用进程创建时间筛选 ...

C#和Asp.net下excel进程一被打开,有时就无法关闭,尤其是website.对关闭该进程有过GC、release等方法,但这些方法并不是在所有情况下均适用

于是提出了kill process的方法,目前我见过的方法多是用进程创建时间筛选excel.exe进程,然后kill 。这样的方法是不精确的,也是不安全的,通过对网上一些关于Api运用文章的阅读,我找到了更为直接精确找到这个process并kill的方法

以下就是代码

复制代码 代码如下:

usingSystem.Runtime.InteropServices;

[DllImport("User32.dll",CharSet=CharSet.Auto)]

publicstaticexternintGetWindowThreadProcessId(IntPtrhwnd,outintID);

protectedvoidButton1_Click(objectsender,EventArgse)

{

Excel.ApplicationClassexcel=newMicrosoft.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);

IntPtrt=newIntPtr(excel.Hwnd);

intk=0;

GetWindowThreadProcessId(t,outk);

System.Diagnostics.Processp=System.Diagnostics.Process.GetProcessById(k);

p.Kill();

}

以上代码百分百成功的关闭excel.exe进程

我的做法是结合两者,先释放资源,然后关闭进程。

同时网上说避免使用GC.Collect 方法 (),因为会导致整个clr进行gc,影响你的性能.所以我也没有调用GC.Collect

赞助本站

人工智能实验室

相关热词: excel c

AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港