欢迎来到山村网

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

2019-03-02 10:12:10浏览:274 来源:山村网   
核心摘要:C#和Asp.net下excel进程一被打开,有时就无法关闭,尤其是website.对关闭该进程有过GC、release等方法,但这些方法并不是在所有情
C#和Asp.net下excel进程一被打开,有时就无法关闭,尤其是website.对关闭该进程有过GC、release等方法,但这些方法并不是在所有情况下均适用

于是提出了killprocess的方法,目前我见过的方法多是用进程创建时间筛选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

(责任编辑:豆豆)
下一篇:

Flex 改变树结点图标的2种方法介绍

上一篇:

C#数据类型转换的几种形式

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com