C#調(diào)用Excel與附加代碼
看了C#調(diào)用Excel之后,無意中想起2年前做的一個小項目,自己也遇到過Excel的進程無法結束掉的這種怪問題,最終還是解決了,其實解決的原理很簡單,Excel是一個很特殊的東西,所有對它的操作都是獨占的,因此就有必要在資源釋放上嚴格進行。為了更好的跟大家交流,也同時幫助那些正在被困惑的程序員朋友們,下面就在C#調(diào)用Excel附上我以前的一段小代碼,為了能夠更快更容易說明問題,代碼經(jīng)過了刪減,只保存了結構的完整性,但不保證能夠順利編譯通過,代碼如下:
- using Execl = Microsoft.Office.Interop.Excel;
- try
- {
- Microsoft.Office.Interop.Excel.Application excel =
new Microsoft.Office.Interop.Excel.Application();- Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open
(lujing2, System.Type.Missing, false, System.Type.Missing, System.Type.
Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.
Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);- excel.Visible = true;
- Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.
Interop.Excel.Worksheet)workbook.Worksheets.get_Item- //開始執(zhí)行Excel操作
- if (excel.ActiveWorkbook.Saved == false)
- {
- excel.ActiveWorkbook.Save();
- }
- excel.Quit();
- excel = null;
- Application.Exit();
- GC.Collect(System.GC.GetGeneration(worksheet));
- GC.Collect(System.GC.GetGeneration(workbook));
- GC.Collect(System.GC.GetGeneration(excel));
- }
- catch
- {
- }
- finally
- {
- GC.Collect();
- }
同時,這里有一個比較有爭議的問題,我特此聲明下:微軟強烈建議不要通過GC.Collect方法來強制執(zhí)行垃圾手機,因為那會妨礙GC本身的工作方式。只有在明確知道有大量對象停止引用時,
才考慮使用GC.Collect方法來調(diào)用收集器,以上介紹C#調(diào)用Excel
【編輯推薦】