2010-06-16 48 views
1

我使用上述調用在完成後釋放一些Excel對象。是否有必要將引用設置爲null(如下面的代碼)?Marshal.ReleaseComObject(...)問題

var dateCol = sheet1.get_Range("C4", "C" + rowOffset); 
dateCol.NumberFormat = "Text"; 
Marshal.ReleaseComObject(dateCol); 
dateCol = null; 
+2

Excel的互操作是有點黑魔法, 恕我直言。 null不會傷害。 – Nate 2010-06-16 14:24:38

回答

1

這是我一直用它工作得很好

using Excel = Microsoft.Office.Interop.Excel; 

    Excel.ApplicationClass _Excel; 
    Excel.Workbook WB; 
    Excel.Worksheet WS; 

try 
    { 

    _Excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
    WB = _Excel.Workbooks.Open("FILENAME", 
     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); 

     //do something 

    } 
    catch (Exception ex) 
    { 
     WB.Close(false, Type.Missing, Type.Missing); 

     throw; 
    } 
    finally 
    { 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 

     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB); 

     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel); 


    } 

做一個

System.Runtime.InteropServices.Marshal.FinalReleaseComObject 

在所有引用Excel對象

+0

謝謝!我一定會使用它。似乎有時候Excel會掛起,儘管我的代碼在上面......所以看起來這是要走的路。 – 2010-06-16 14:39:07