這段時間在VS 的WebForm 方式下對Excel 進行操作,遇到一個最為頭疼的問題就是對Excel操作完畢後Excel不能夠正常關閉,系統退出後,Excel總是駐留在內存中。但是這段代碼放到WinForm的程序中又沒有問題。在網上進行了查找也沒有找到有效可行的辦法。經過無數次的嘗試,終於解決如下:
原來書寫如下:
private Excel.Application m_app;
private Excel.Workbook m_workbook;
this.m_app = new Excel.ApplicationClass();
this.m_app.DisplayAlerts = false;
this.m_workbook = this.m_app.Workbooks.Open(sFilePath, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value );
修改後如下:
private Excel.Application m_app;
private Excel.Workbooks m_workbooks;
private Excel.Workbook m_workbook;
this.m_app = new Excel.ApplicationClass();
this.m_app.DisplayAlerts = false;
m_workbooks = this.m_app.Workbooks;
this.m_workbook = this.m_workbooks.Open(sFilePath, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value );
同樣對Sheet的操作如下
修改前如下:
Excel._Worksheet worksheet1 = null;
worksheet1 = (Excel._Worksheet) this.m_workbook.Worksheets.get_Item(sSheetName);
修改後如下:
Excel.Sheets sheets = null ;
Excel._Worksheet worksheet1 = null;
sheets = this.m_workbook.Worksheets;
worksheet1 = (Excel._Worksheet) sheets.get_Item(sSheetName);
發現區別了麼?原來Workbooks,Worksheets這兩個類沒有被實例化就直接使用了,造成該類不能夠被回收。最終造成Excel在內存的駐留。
最終以如下方式釋放。
private void ReleaseAllRef(Object obj)
{
try
{
if (obj != null )
{
while (Marshal.ReleaseComObject(obj) > 1);
}
}
finally
{
obj = null;
}
}
private void Release()
{
if (m_app != null )
{
m_app.Quit() ;
}
ReleaseAllRef(m_workbook) ;
m_workbook = null ;
ReleaseAllRef(m_workbooks) ;
m_workbooks = null ;
ReleaseAllRef(m_app) ;
m_app = null ;
System.GC.Collect() ;
}