解析c#操作excel后關(guān)閉excel.exe的方法
更新時(shí)間:2013年07月09日 09:09:34 作者:
C#和Asp.net下excel進(jìn)程一被打開(kāi),有時(shí)就無(wú)法關(guān)閉,尤其是website.對(duì)關(guān)閉該進(jìn)程有過(guò)GC、release等方法,但這些方法并不是在所有情況下均適用
于是提出了kill process的方法,目前我見(jiàn)過(guò)的方法多是用進(jìn)程創(chuàng)建時(shí)間篩選excel.exe進(jìn)程,然后kill 。這樣的方法是不精確的,也是不安全的,通過(guò)對(duì)網(wǎng)上一些關(guān)于Api運(yùn)用文章的閱讀,我找到了更為直接精確找到這個(gè)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();
}
以上代碼百分百成功的關(guān)閉excel.exe進(jìn)程
我的做法是結(jié)合兩者,先釋放資源,然后關(guān)閉進(jìn)程。
同時(shí)網(wǎng)上說(shuō)避免使用GC.Collect 方法 (),因?yàn)闀?huì)導(dǎo)致整個(gè)clr進(jìn)行g(shù)c,影響你的性能.所以我也沒(méi)有調(diào)用GC.Collect
以下就是代碼
復(fù)制代碼 代碼如下:
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();
}
以上代碼百分百成功的關(guān)閉excel.exe進(jìn)程
我的做法是結(jié)合兩者,先釋放資源,然后關(guān)閉進(jìn)程。
同時(shí)網(wǎng)上說(shuō)避免使用GC.Collect 方法 (),因?yàn)闀?huì)導(dǎo)致整個(gè)clr進(jìn)行g(shù)c,影響你的性能.所以我也沒(méi)有調(diào)用GC.Collect
相關(guān)文章
datagridview實(shí)現(xiàn)手動(dòng)添加行數(shù)據(jù)
這篇文章主要介紹了datagridview實(shí)現(xiàn)手動(dòng)添加行數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04測(cè)試框架nunit之a(chǎn)ssertion斷言使用詳解
NUnit是.Net平臺(tái)的測(cè)試框架,廣泛用于.Net平臺(tái)的單元測(cè)試和回歸測(cè)試中,下面我們用示例詳細(xì)學(xué)習(xí)一下他的使用方法2014-01-01采用easyui tree編寫(xiě)簡(jiǎn)單角色權(quán)限代碼的方法
本文主要介紹了如何采用easyui tree編寫(xiě)簡(jiǎn)單角色權(quán)限代碼,文章思路清晰,需要的朋友可以參考下2015-07-07unity 切換場(chǎng)景不銷毀物體問(wèn)題的解決
這篇文章主要介紹了unity 切換場(chǎng)景不銷毀物體問(wèn)題的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04C#使用Socket實(shí)現(xiàn)發(fā)送和接收?qǐng)D片的方法
這篇文章主要介紹了C#使用Socket實(shí)現(xiàn)發(fā)送和接收?qǐng)D片的方法,涉及C#操作socket發(fā)送與接收文件的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-04-04