ASP.NET中调用Excel的问题

如果需要在ASP。NET的程序里调用Office的组件,例如Excel,代码写起来并不复杂

首先引用Microsoft.Office.Interop.Excel(注意,必须先装PIAs,可以是OfficeXP的PIAs,但推荐如果是Office 2003的话,就装Office2003PIAs

代码大致如下,看了一些网上的介绍,说是要用System.Runtime.InteropServices.Marshal.ReleaseComObject来显式释放,但测试的结果仍然无效

在VS 2003和VS 2005都是这样的

这个问题咨询了微软的技术支持,最后的结果是不建议用这种服务器端调用Office组件的技术

private void Button2_Click(object sender, System.EventArgs e)
  {
   object missing=Type.Missing;
   Excel.Application app=new Excel.ApplicationClass();
   Excel.Workbook wb=app.Workbooks.Add(missing);
   Excel.Worksheet ws=(Excel.Worksheet)wb.Worksheets.get_Item(1);
   ws.Cells[1,1]="Hey,man!I am here!";
   string fileName=Server.MapPath(@"Test.xls");
   if(System.IO.File.Exists(fileName))
    System.IO.File.Delete(fileName);

wb.Close(true,fileName,missing);
   NAR(ws);
   NAR(wb);
   app.Quit();
   NAR(app);
   GC.Collect();
  }

private void NAR(object o)
  {
   try
   {
    System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
   }
   catch {}
   finally
   {
    o = null;
   }
  }

 

下面是微软工程师的回答

您好 陈希章
我给您试了,确实是有这个问题。
我反复查了相关文档后,发现这个问题是由于Server-Side调用Automation引起的。
这是一个KnowIssue,这种应用是受到Microsoft限制的。
我们不支持和建议使用Server-Side的程序去掉用Automation,因为可能会引起很多问题。
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when run in this environment.
您可以从以下的KB中看到详细的相关信息
http://support.microsoft.com/kb/257757/
您可能必须更改您的设计来回避这个问题了。
很抱歉,对于这个问题,我们也无法提供给您可用的解决方法。
可能是由于Server-side的程序设计使然,他不同于winform的程序,确实有些类或是组件当在Server-side调用时却是会引起很多的问题。

原文地址:https://www.cnblogs.com/chenxizhang/p/1269702.html