使用Excel COM组件导出数据后释放Excel资源

来源:互联网 发布:中国人工智能上市企业 编辑:程序博客网 时间:2024/06/05 05:56

有个老项目是用VS2003做的,
下面是导出数据代码

C# code
Response.ContentType = "application/x-msexcel";Response.ContentEncoding = System.Text.Encoding.Default;Response.AddHeader("content-disposition","attachment; filename=PhoneModelColor.xls");DataTable dt = (DataTable)Session["Color"];StringBuilder sb = new StringBuilder(); sb.Append("<META Http-Equiv='Content-Type' Content='text/html; charset=gb2312'>");sb.Append("<table border='1'>");sb.Append("<tr><td>Phone Model</td><td>Color Code</td><td>Chinese</td><td>English</td><td>Description</td></tr>");for(int i=0;i<dt.Rows.Count;i++){ sb.Append("<tr>"); sb.Append("<td>"+dt.Rows[i]["Name"].ToString()+"</td>"); sb.Append("<td>"+"'"+dt.Rows[i]["Color_Code"].ToString()+"</td>"); sb.Append("<td>"+dt.Rows[i]["NameCh"].ToString()+"</td>"); sb.Append("<td>"+dt.Rows[i]["NameEng"].ToString()+"</td>"); sb.Append("<td>"+dt.Rows[i]["Desc"].ToString()+"</td>"); sb.Append("</tr>");}sb.Append("</table>");Response.Write(sb.ToString());Response.End();



由于客户全部将OFFICE升级成2007
上面方法导出的EXCEL出现很多问题。

导出EXCEL控件也有很多,我现在是想说说使用 Microsoft.Office.Interop.Excel.dll 出现的一个大问题:Excel释放(关闭Excel进程)

在网上搜索相关的信息基本上就是2种解决方法。
1,强制垃圾回收。
  使用GC.Collect();强制垃圾回收。但是效果不明显,有时候根本不起作用。

2,杀掉Excel进程。
  执行完EXCEL然后杀掉进程,虽然这100%能杀掉,但是用户需要权限,还得修改服务器的设置(BS网站很难实现)。再说容易误删,这样做是有效果,但是很危险。

到底是为什么无法释放Excel呢?
最后发现一篇MSDN上文章:http://support.microsoft.com/kb/317109
大家可以看看!

文章的意思是创建的每个对象都得释放掉,Excel进程才会关闭。
如果你写的代码导出Excel老是无法关闭Excel,可以看看我下面的代码。

C# code
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。

http://support.microsoft.com/kb/317109

 

原创粉丝点击