I am working with Excel Interop COM object. I am writing a method in which I am opening and closing an Excel application followed by opening an Excel workbook and sheet. After I'm done working on them I am closing both the application and workbook. My problem is that this method can be called repeatedly several times and when the sheet and app are closing I get from the Excel application a message if I want to save the changes I've made. The method get stuck until I press "No" but I can't tell the user to press it every time.
How can I close the application without receiving this message or at least answer it by code?
These are the methods I'm using to close the application and workbook:
private void FreeWorkSheetResources(Excel.Worksheet sheet)
{
Marshal.ReleaseComObject(sheet);
sheet = null;
}
private void FreeWorkBookResources()
{
if (_excelSheets != null)
{
Marshal.ReleaseComObject(_excelSheets);
_excelSheets = null;
}
_excelWorkBook.Close();
Marshal.ReleaseComObject(_excelWorkBook);
_excelWorkBook = null;
}
private void FreeApplicationResources()
{
_app.Quit();
Marshal.ReleaseComObject(_app);
_app = null;
GC.Collect();
}
And this is the way I'm using them:
if (_app == null)
{
_app = new Excel.Application();
}
if (_excelWorkBook == null)
{
_excelWorkBook = GetWorkBook(_filePath);
}
....
....
FreeWorkBookResources();
FreeApplicationResources();
While Closing Your Excel WorkBook you can use following Statements:
object misValue = System.Reflection.Missing.Value;
xlWorkBook.Close(false, misValue, misValue);
My problem was similar. I needed to generate Excel Sheet, then convert it to PDF. My problem was that the Excel App was displaying and notifying me to save before Exit. The solution was setting .Visible = flase
and .DisplayAlerts = False
Thanks to @adil
Try this:
excelApp.DisplayAlerts = False;
//save and close your workbook
excelApp.DisplayAlerts = True;
Do this when closing workbook.
_excelWorkBook.Close(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With