Question posted 2011 · +9 upvotes
I have a windows service that opens up an Excel spreadsheet via the Microsoft.Office.Interop.Excel.Application object.
Application xlApp = new Application();
Workbook workbook = xlApp.Workbooks.Open(fileName, 2, false);
...
...
workbook.Close();
xlApp.Quit();
I would like to kill the EXCEL.exe process that is left running after it is done working with the workbook.
I’ve tried the following with no success…
// This returns a processId of 0
IntPtr processId;
GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), out processId);
Process p = Process.GetProcessById(processId.ToInt32());
p.Kill();
Anyone have any ideas as to how I can do this via a Windows Service?
Accepted answer +10 upvotes
Properly closing the open Excel workbook and quitting the app is extremely difficult. If I can find the links I’ll post them, but essentially you must clean up all references to any COM object that you create. This includes everything from ODBCConnections (data connections), Worksheets, Workbooks, and the Excel application. A combination I got to work involved garbage collection and the System.Runtime.InteropServices.Marshal object:
// Garbage collecting
GC.Collect();
GC.WaitForPendingFinalizers();
// Clean up references to all COM objects
// As per above, you're just using a Workbook and Excel Application instance, so release them:
workbook.Close(false, Missing.Value, Missing.Value);
xlApp.Quit();
Marshal.FinalReleaseComObject(workbook);
Marshal.FinalReleaseComObject(xlApp);
Like you mentioned, looping through and killing each Excel process is usually not a good idea, since if you’re running this as a Windows app you may close Excel on your user, or in a service also close an instance of Excel that is running via some other program.
Edit: See this question for more info.
Excel VBA objects referenced (5)
Application— Using events with the Application objectApplication— Working with Other ApplicationsInterop.Excel— Using events with Excel objectsInterop.Excel— Using Excel worksheet functions in Visual BasicMicrosoft.Office— Controlling One Microsoft Office Application from Another
Top excel Q&A (6)
- Shortcut to Apply a Formula to an Entire Column in Excel +335 (2011)
- How should I escape commas and speech marks in CSV files so they work in Excel? +136 (2012)
- Convert xlsx to csv in linux command line +96 (2012)
- How to create a link inside a cell using EPPlus +50 (2011)
- IF statement: how to leave cell blank if condition is false ("" does not work) +44 (2013)
- T-SQL: Export to new Excel file +44 (2012)
excel solutions on this site
.