这段时间在vs 2003 的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() ;
}