Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing Excel application with Excel Interop without save message

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();
like image 623
Yonatan Nir Avatar asked Nov 14 '13 12:11

Yonatan Nir


4 Answers

While Closing Your Excel WorkBook you can use following Statements:

object misValue = System.Reflection.Missing.Value;
xlWorkBook.Close(false, misValue, misValue);
like image 78
Sudhakar Tillapudi Avatar answered Sep 25 '22 15:09

Sudhakar Tillapudi


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

like image 45
Cogent Avatar answered Sep 23 '22 15:09

Cogent


Try this:

excelApp.DisplayAlerts = False;
//save and close your workbook
excelApp.DisplayAlerts = True;
like image 27
adil Avatar answered Sep 21 '22 15:09

adil


Do this when closing workbook.

_excelWorkBook.Close(true);
like image 23
Muhammad Umar Avatar answered Sep 25 '22 15:09

Muhammad Umar