2012-01-04 125 views
2

當我運行下面的代碼時,它仍然不釋放excel對象。如何清理Excel中的Excel互操作對象#

enter image description here

public static List<string> GetExcelSheets(string FilePath) 
     { 
      Microsoft.Office.Interop.Excel.Application ExcelObj = null; 
      Workbook theWorkbook = null; 
      Sheets sheets = null; 

      try 
      { 
       ExcelObj = new Microsoft.Office.Interop.Excel.Application(); 
       if (ExcelObj == null) 
       { 
        MessageBox.Show("ERROR: EXCEL couldn't be started!"); 
        System.Windows.Forms.Application.Exit(); 
       } 

       theWorkbook = ExcelObj.Workbooks.Open(FilePath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true); 
       List<string> excelSheets = new List<string>(); 

       sheets = theWorkbook.Worksheets; 
       foreach (Worksheet item in sheets) 
       { 
        excelSheets.Add(item.Name); 
       } 

       return excelSheets; 
      } 
      catch (Exception ex) 
      { 
       return new List<string>(); 
      } 
      finally 
      { 
       // Clean up. 
       releaseObject(sheets); 
       releaseObject(theWorkbook); 
       releaseObject(ExcelObj); 
      } 
     } 

     private static void releaseObject(object obj) 
     { 
      try 
      { 
       System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); 
       obj = null; 
      } 
      catch (Exception ex) 
      { 
       obj = null; 
       MessageBox.Show("Exception Occured while releasing object " + ex.ToString()); 
      } 
      finally 
      { 
       GC.Collect(); 
      } 
     } 
+1

相關:HTTP://計算器。 com/questions/158706 /如何正確清理excel-interop-objects-in-c-sharp – JMax 2012-01-04 14:21:31

回答

0

你忘了保持到ExcelObj.Workbooks參考,並釋放它:

Workbooks workbooks; 
... 
workbooks = ExcelObj.Workbooks; 
theWorkbook = workbooks.Open(... 
... 
releaseObject(sheets); 
releaseObject(theWorkbook); 
releaseObject(workbooks); 
releaseObject(ExcelObj); 
-1

試試這個代碼:

ExcelObj.Quit(); 
+0

在futu而不是增加毫無意義的數字來填補最小長度,我建議增加一個解釋,無論如何簡短。這也可以避開那些討厭的VLQ標誌。 – 2015-05-08 00:42:13