Excel在.Net下驻留内存的解决方法
原来书写如下:
以下是引用片段:
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() ;
}