2

I'm using excel to populate some data and create a report using the following code:

Excel.Application app = new Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(templatePath);
Excel.Worksheet worksheet = workbook.Worksheets[1];

worksheet.Cells[1, 2] = myInbox.FolderPath;
worksheet.Cells[2, 2] = DateTime.Today.ToShortDateString();
worksheet.Cells[2, 4] = DateTime.Now.ToShortTimeString();

app.Visible = true;
workbook.RefreshAll();

This all seems to work fine, however when I look at task manager I notice several instances of excel open in "background processes". There appears to be one instance of excel for every time I have run the code despite closing excel each time.

These background processes don't even appear if I open Excel manually.

Oliver
  • 87
  • 1
  • 10

1 Answers1

4

Ok so I found the answer fairly quickly, I was not releasing the interop objects properly which is why they persisted even after the application quit.

I've included the link to the correct answer below but for reference the code to close these objects is:

Excel.Application app = new Excel.Application();
Excel.Workbooks workbooks = app.Workbooks;
Excel.Workbook workbook = workbooks.Open(templatePath);
Excel.Worksheet worksheet = workbook.Worksheets[1];

//do stuff to worksheet here

System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

Clean up excel interop objects

so I've learn't a little about garbage collection today.

Community
  • 1
  • 1
Oliver
  • 87
  • 1
  • 10