2012-01-04 59 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