【ZT】使用Excel COM组件导出数据后释放Excel资源
作者:veekchen 日期:2010-06-01
以前做过的项目曾经出现过此问题,解决方法是杀掉excel.exe的进程,指标不治本,且不安全。
今天偶尔逛csdn看到一解决此问题的方法,特此共享。(注意:暂时只测试过office03能通过)
【ZT】内容:
到底是为什么无法释放Excel呢?
最后发现一篇MSDN上文章:http://support.microsoft.com/kb/317109
大家可以看看!
文章的意思是创建的每个对象都得释放掉,Excel进程才会关闭。
如果你写的代码导出Excel老是无法关闭Excel,可以看看我下面的代码。
private void ExportExcel(DataTable dt, string _strTitle)
{
string newpath = Server.MapPath(".") + @"\" + Guid.NewGuid() + ".xls";
_excel.Application app = new _excel.Application();
_excel.Workbooks wbooks = app.Workbooks;
_excel.Workbook wbook = wbooks.Add(System.Reflection.Missing.Value);
//VS2003中最好不要如下创建
// _excel.Workbook wbook = app.Workbooks.Add(System.Reflection.Missing.Value);
_excel.Worksheet tsheet = (_excel.Worksheet)wbook.ActiveSheet;
//为 tsheet.Cells 创建 Range ,方便释放资源
_excel.Range rans = (_excel.Range)tsheet.Cells;
//创建ran为了下面赋值时候使用
_excel.Range ran = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
ran = (_excel.Range)rans[i + 1, j + 1];
ran.Value2 = dt.Rows[i][j];
NAR(ran);
//不要如下方式赋值
//tsheet.Cells[i + 1, j + 1] = dt.Rows[i][j];
}
}
NAR(rans);
NAR(tsheet);
//保存信息
wbook.Close(true,newpath, System.Reflection.Missing.Value);
NAR(wbook);
NAR(wbooks);
app.Quit();
NAR(app);
}
/// <summary>
/// 释放资源
/// </summary>
/// <param name="o"></param>
private void NAR(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch { }
finally
{
o = null;
}
}
经过测试VS2003 和VS2005中都可以正常的自动关闭Excel。
今天偶尔逛csdn看到一解决此问题的方法,特此共享。(注意:暂时只测试过office03能通过)
【ZT】内容:
到底是为什么无法释放Excel呢?
最后发现一篇MSDN上文章:http://support.microsoft.com/kb/317109
大家可以看看!
文章的意思是创建的每个对象都得释放掉,Excel进程才会关闭。
如果你写的代码导出Excel老是无法关闭Excel,可以看看我下面的代码。
private void ExportExcel(DataTable dt, string _strTitle)
{
string newpath = Server.MapPath(".") + @"\" + Guid.NewGuid() + ".xls";
_excel.Application app = new _excel.Application();
_excel.Workbooks wbooks = app.Workbooks;
_excel.Workbook wbook = wbooks.Add(System.Reflection.Missing.Value);
//VS2003中最好不要如下创建
// _excel.Workbook wbook = app.Workbooks.Add(System.Reflection.Missing.Value);
_excel.Worksheet tsheet = (_excel.Worksheet)wbook.ActiveSheet;
//为 tsheet.Cells 创建 Range ,方便释放资源
_excel.Range rans = (_excel.Range)tsheet.Cells;
//创建ran为了下面赋值时候使用
_excel.Range ran = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
ran = (_excel.Range)rans[i + 1, j + 1];
ran.Value2 = dt.Rows[i][j];
NAR(ran);
//不要如下方式赋值
//tsheet.Cells[i + 1, j + 1] = dt.Rows[i][j];
}
}
NAR(rans);
NAR(tsheet);
//保存信息
wbook.Close(true,newpath, System.Reflection.Missing.Value);
NAR(wbook);
NAR(wbooks);
app.Quit();
NAR(app);
}
/// <summary>
/// 释放资源
/// </summary>
/// <param name="o"></param>
private void NAR(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch { }
finally
{
o = null;
}
}
经过测试VS2003 和VS2005中都可以正常的自动关闭Excel。
评论: 0 | 引用: 0 | 查看次数: 107
发表评论
上一篇
下一篇


文章来自:
Tags:
相关日志:






