2

I am using the Excel interop in C# in my web site project to parse an Excel file and convert it to a text file. The sample code is as following. It worked well in the debug mode. But in Task Manager I often see two Excel are running, why?. In addition after deployed the web site to IIS, the excel.exe will not quit. My project is a web site project in VS 2010 (Ultimate). My machine is Windows Server 2008, which means I should have IIS 7. But when I run the inetmgr, it shows IIS version 6 (after googling, I confirmed that my IIS should be still 7, the management tool is 6).

So my question is why Excel is not quitting after I deployed to IIS?

Excel.Application excel=new Excel.Application();
Excel.Workbooks wbs=excel.Workbooks;
Excel.Workbook wb=wbs.Open(…);

Try 
{
   …
   Foreach(Excel.Worksheet sheet in wb.Sheets)
   {
      …
      Marshal.RealseComObject(sheet);
   }
   …
}

Catch()
{
}

Finally
{
   wb.Close(false, missing, missing);
   while (Marshal.ReleaseComObject(wb)!=0)
   {
   }
   wb=null;
   while (Marshal.ReleaseComObject(wbs)!=0)
   {
   }
   wbs=null;

   excel.Quit();
   while (Marshal.ReleaseComObject(excel)!=0)
   {
   }
   excel=null;
   GC.Collect();
   GC.WaitForPendingFinalizers();
}

Updated: it turned out it was because wbs.Open(…) threw an exception.

I found the solution from following link and it fixed my problem. Cannot open Excel file in C#

Community
  • 1
  • 1
GLP
  • 3,441
  • 20
  • 59
  • 91
  • Try to make the Excel instances visible so that you'll be able to check their state. Moreover if you don't use advanced features you should use another library to read your Excel files: EPPlus is a good choice. If you have performance issue then you can fallback to NPOI. – Pragmateek Nov 05 '13 at 20:38
  • Perhaps, you could turn the **update** into an answer. It is ok to self-answer ([source](http://stackoverflow.com/help/self-answer)). – Andre Silva Dec 04 '14 at 19:51
  • 1
    You absolutely should not use Excel Interop in your web application. Microsoft [warns of the dangers](http://support.microsoft.com/kb/257757). Not only is it unreliable, it's also messy to work with code-wise. Any of the popular libraries such as EPPlus or NPOI of Open Office XML SDK should meet your needs. – mason Dec 04 '14 at 19:54

0 Answers0