0

Simple code, and I thought it should kill Excel. But the task manager says this leaves an instance of Excel running. What am I missing? Thank you.

using Microsoft.Office.Interop.Excel;
//Stuff...
// Launch dialog picker that return path to Excel file, in string
// called excelTemplate
Microsoft.Office.Interop.Excel.Application xlTemp = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = xlTemp.Workbooks.Open(excelTemplate);
xlTemp.DisplayAlerts = false;

// Poke through individual sheets, get some info from them

 workbook.Close();
 xlTemp.Quit();
  • 1
    Possible duplicate of [Why does Microsoft.Office.Interop.Excel.Application.Quit() leave the background process running?](https://stackoverflow.com/questions/27930307/why-does-microsoft-office-interop-excel-application-quit-leave-the-background) – mjwills Nov 13 '18 at 01:24
  • See also my comment at https://stackoverflow.com/questions/50927453/how-to-dispose-interop-excel-application-and-workbook-correctly . – mjwills Nov 13 '18 at 01:24
  • It occurred to me that the search through the worksheets probably leaves it on a different worksheet than when it opened, but DisplayAlerts = false would suppress the "do you want to save" box.... So I tried adding object misValue = System.Reflection.Missing.Value; and specifying workbook.Close(false, misValue, misValue); That did not help. – Aram Schiffman Nov 13 '18 at 01:35
  • Excel Interop was designed to make developers hate their lives. I recommend checking out EPPlus. You don't need an open instance of Excel running to open a spreadsheet and read it. You don't even need Excel installed. You just open it like a document and read what you want. https://github.com/JanKallman/EPPlus – Scott Hannen Nov 13 '18 at 02:25

2 Answers2

0
Application xlTemp = new Application();
Workbooks workbooks = xlTemp.Workbooks;
Workbook workbook = workbooks.Open(excelTemplate);

// Do stuff.

workbook.Close();
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);
xlTemp.Quit();
Marshal.ReleaseComObject(xlTemp);

Aside from needing to release each COM object, note also that by doing xlTemp.Workbooks.Open, you're leaking a COM reference by not assigning xlTemp.Workbooks to a variable that can be released later.

Justin
  • 680
  • 9
  • 19
-1

You can used #using to automatically dispose the application.

using(Microsoft.Office.Interop.Excel.Application xlTemp = new 
Microsoft.Office.Interop.Excel.Application())
{
   Workbook workbook = xlTemp.Workbooks.Open(excelTemplate);
   xlTemp.DisplayAlerts = false;

   // Poke through individual sheets, get some info from them

   workbook.Close();
}
Tuan Zaidi
  • 343
  • 1
  • 14