tags:

views:

91

answers:

4

Lets say I have an Excel file named "DataSheet.xls" open. How can I kill that Excel file using c#?

A: 

off hand don't have the code as such. but generally, in the past i'd have used a couple of api calls to do this. first, you'd get the window handle (hWnd) and then you'd use the sendmessage api call with the wm_close parameter.

that's about all i can remember -it's been about 10 yrs since i had to do that kinda stuff, so the field may have changed since then :)

jim
Thank you very much for your help.
Rabin
+1  A: 

The Process class would allow you to kill a process. You could inspect all running excel.exe processes, get the main window handle for the process, check whether the caption of that window contains the name of the XLS file and then kill the process for that window.

Otherwise you could use the Office COM classes to talk to Excel. This may also allow you to shut down open workbooks.

Thorsten Dittmar
Thank you very much for your help.
Rabin
+2  A: 

It's very likely that a single process will contain multiple open workbooks. Especially because Excel prefers to re-use an existing instance when opening files from Explorer, Outlook, etc. instead of creating a new process for each workbook.

Not to mention killing the process will require you to either 1) close the main window which will prompt if there's unsaved changes or 2) forcefully kill the process which will likely cause Excel to show its crash recovery options the next time you launch it.

The best course of action is to use the Excel COM API to close the workbooks. You can use the Marshal.GetActiveObject method to get a running instance of Excel and then refer to the Office developer reference for more information about how to close specific named workbooks without prompting.

Josh Einstein
Thank you very much for your help.
Rabin
+3  A: 
using Excel = Microsoft.Office.Interop.Excel;
(...)
var app = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
// I have english excel, but another culture and need to use english culture to use excel calls...
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
app.Workbooks["DataSheet"].Close(false, false, false);
simendsjo
Thank you very much for your help.
Rabin
Is there any reason this does not work in FormClosed or FormClosing?
Rabin
Shouldn't be.. Are you sure it's getting called?
simendsjo