c#操作excel后关闭excel.exe的方法(转)

本文介绍了一种在C#和ASP.NET环境下彻底关闭Excel进程的方法。通过先释放资源再使用API精确查找并杀死进程的方式,有效解决了进程无法正常关闭的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

。网上的一种说法,关闭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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值