c#操作excel后关闭excel.exe的方法
2009-10-03 05:59
363 查看
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
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的方法
- c#操作excel后关闭excel.exe的方法
- c#操作excel后关闭excel.exe的方法
- c#操作excel后关闭excel.exe的方法
- c#操作excel后关闭excel.exe的方法
- c#操作excel后关闭excel.exe的方法
- c#操作excel后关闭excel.exe的方法
- 解析c#操作excel后关闭excel.exe的方法
- C# 操作excel 关闭excel的方法
- 【转】.NET引用Excel操作时无法关闭Excel.exe进程的解决方法
- C#操作Excel(创建、打开、读写、保存)几种方法的总结
- C# 操作Excel是遇到的80070005错误-解决方法
- C#利用com操作excel释放进程的解决方法
- C#操作Excel时,Excel常用的方法和属性zz
- C#操作excel(多种方法比较)
- C# 导出数据到Excel后,销毁Excel.exe进程的方法
- C#操作Excel(创建、打开、读写、保存)几种方法的总结
- C#操作excel(多种方法比较)
- C#导出Excel后关闭进程(EXCEL.EXE)释放资源的解决方案
- 转载:C#中操作Excel的方法