c#操作excel后关闭excel.exe的方法
生活随笔
收集整理的這篇文章主要介紹了
c#操作excel后关闭excel.exe的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
轉載于:https://www.cnblogs.com/freedom831215/archive/2009/10/03/1577622.html
總結
以上是生活随笔為你收集整理的c#操作excel后关闭excel.exe的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于MapWinGis的开发探索(三)-
- 下一篇: c#3.0关于JSON简单操作的实用帮助