Is there a better way than to Kill() a process that archives the same result. When I Kill() an Excel process, the next time I open any Excel Worksheet, "Document Recovery" sidebar is opened, which I do not want to do.
+5
A:
Add a .Net reference to Microsoft.Office.Interop.Excel
. Then take a look at the following code I knocked together:
Microsoft.Office.Interop.Excel.ApplicationClass _excel;
Microsoft.Office.Interop.Excel.Workbook _workBook;
private void Form1_Load(object sender, EventArgs e)
{
_excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
_excel.Visible = true;
// Open the workbook
_workBook = _excel.Workbooks.Open(@"DataSheet.xls",
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
}
private void btn_Close_Click(object sender, EventArgs e)
{
GC.Collect();
GC.WaitForPendingFinalizers();
_workBook.Close(false, Type.Missing, Type.Missing);
_excel.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_workBook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_excel);
}
GenericTypeTea
2010-07-01 10:49:12
I tried this but the next time I open the same file, it gives out error.
Rabin
2010-07-01 10:51:55
@Rabin - provide a code example.
GenericTypeTea
2010-07-01 10:52:27
Btw, `Process.Close` is an alias for `Process.Dispose` - it releases your copy of the process handle rather than shut down a running process.
Tim Robinson
2010-07-01 11:06:04
@Tim - My mistake! Updated the answer.
GenericTypeTea
2010-07-01 11:07:28
Thanks for your help Generic.
Rabin
2010-07-02 09:46:25
+1
A:
Since this is Excel, how about actually talking to Excel and asking it to close nicely? You can do this using COM.
Lasse V. Karlsen
2010-07-01 10:52:52
Say I want to close DataSheet.xls nicely. How do I do it using COM? Any code example?
Rabin
2010-07-01 11:05:29
See @ [GenericTypeTea](http://stackoverflow.com/users/44269/generictypetea) 's [answer](http://stackoverflow.com/questions/3157051/better-option-than-process-kill/3157061#3157061).
Lasse V. Karlsen
2010-07-01 11:31:41
+1
A:
Not sure if this will help with Excel running in a web browser. If you can grab the instance of Excel that's running you can find the workbook you want to close...
try
{
// Grab a reference to an open instance of Excel
var oExcelApp =
(Microsoft.Office.Interop.Excel.Application)
Marshal.GetActiveObject("Excel.Application");
// Loop around the workbooks to find the one you want to close
for (int i = 1; i <= oExcelApp.Workbooks.Count; i++)
{
if (oExcelApp.Workbooks[i].Name == "requiredname")
oExcelApp.Workbooks[i].Close(Type.Missing, Type.Missing, Type.Missing);
}
// Clear up...
Marshal.FinalReleaseComObject(oExcelApp);
}
catch(Exception ex)
{
// Something went wrong...
}
Andy Robinson
2010-07-01 11:53:55