常見.NET功能程式碼彙總 (3) 33,徹底關閉Excel程序
阿新 • • 發佈:2022-04-29
33,徹底關閉Excel程序
.NET中使用Excel屬於使用非託管資源,使用完成後一般都要用GC回收資源,但是,呼叫GC的位置不正確,Excel程序可能無法徹底關閉,如下面的程式碼:
static void OpenExcelTest(int j) { //Application excel = null; excel = new Application(); excel.Visible = true; excel.Workbooks.Open("d:\A1000.xla"); Workbook wb = excel.Application.Workbooks.Open("d:\Book1.xlsx"); Worksheet sh = wb.Worksheets.Item["Sheet1"]; object[,] ssss = sh.Range[sh.Cells[1.1], sh.Cells[3, 1]].Value2; Console.WriteLine("opened excel no. {0}", j); Console.ReadLine(); try { //嘗試程式關閉Excel程序 wb.Close(false); sh = null; wb = null; excel.Quit(); } catch (Exception ex) { Console.WriteLine("使用者已經手工結束了Excel程序,內部錯誤訊息:{0}",ex.Message ); } int generation = System.GC.GetGeneration(excel); //No.1 //System.Runtime.InteropServices.Marshal.ReleaseComObject(wb); //System.Runtime.InteropServices.Marshal.ReleaseComObject(sh); //System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); excel = null; //No.2 //GC.Collect(generation); Console.WriteLine("close excel no. {0}", j); Console.ReadLine(); }
在上面的程式碼中,如果取消 No.1,No.2位置處的註釋,方法結束後,Excel程序是無法結束的,解決辦法,只需要把 GC.Collect(); 這行程式碼寫到方法之外即可。
Application excel = null; 這個Excel應用程式物件定義在方法內或者外都是可以的,哪怕定義一個靜態變數,結果都沒有影響。