这段时间在VS2003的WebForm方式下对Excel进行操作,遇到一个最为头疼的问题就是对Excel操作完毕后Excel不能够正常关闭,系统退出后,Excel总是驻留在内存中。但是这段代码放到WinForm的程序中又没有问题。在网上进行了查找也没有找到有效可行的办法。经过无数次的尝试,终于解决如下:
原来书写如下:
privateExcel.Applicationm_app;
privateExcel.Workbookm_workbook;
this.m_app=newExcel.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);
修改后如下:
privateExcel.Applicationm_app;
privateExcel.Workbooksm_workbooks;
privateExcel.Workbookm_workbook;
this.m_app=newExcel.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._Worksheetworksheet1=null;
worksheet1=(Excel._Worksheet)this.m_workbook.Worksheets.get_Item(sSheetName);
修改后如下:
Excel.Sheetssheets=null;
Excel._Worksheetworksheet1=null;
sheets=this.m_workbook.Worksheets;
worksheet1=(Excel._Worksheet)sheets.get_Item(sSheetName);
发现区别了么?原来Workbooks,Worksheets这两个类没有被实例化就直接使用了,造成该类不能够被回收。最终造成Excel在内存的驻留。
最终以如下方式释放。
privatevoidReleaseAllRef(Objectobj)
{
try
{
if(obj!=null)
{
while(Marshal.ReleaseComObject(obj)>1);
}
}
finally
{
obj=null;
}
}
privatevoidRelease()
{
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();
}