-1

I'm using this code to create an Excel report:

 var excel = new Excel.Application();
 foreach (var report in m_reports)
     report.PrintReport(excel.Workbooks.Add().Sheets.Add());
 excel.Visible = true;

Everything works fine. However, when the user manually closes Excel, the Excel process remains open in the Task Manager. Why?

Paul van Brenk
  • 7,450
  • 2
  • 33
  • 38
Artem Makarov
  • 874
  • 3
  • 14
  • 25

2 Answers2

3

Take a look on MSDN about Releasing ComObjects

System.Runtime.InteropServices.Marshal.ReleaseComObject( excel );

also if you are wanting to do something else within that foreach loop I would suggest wrapping your code in the proper code block format for example

 foreach (var report in m_reports)
 {
    report.PrintReport(excel.Workbooks.Add().Sheets.Add());
 }
 excel.Visible = true;
 //Release the ComObject
 System.Runtime.InteropServices.Marshal.ReleaseComObject( excel );
MethodMan
  • 18,625
  • 6
  • 34
  • 52
1

This answer has a good rule: How do I properly clean up Excel interop objects?

"Never use two dots with com objects."

You're declaring workbook and sheet objects without ever releasing them - thats why the process won't quit.

Community
  • 1
  • 1
Alex
  • 266
  • 1
  • 6
  • I thought that release of this objects will kill process and I need to keep Excel program oppened. Thank you, I'll try it a bit later. – Artem Makarov Nov 30 '12 at 04:18