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();
在关闭Excel WorkBook时,您可以使用以下语句:
object misValue = System.Reflection.Missing.Value;
xlWorkBook.Close(false, misValue, misValue);
在关闭工作簿时执行此操作。
_excelWorkBook.Close(true);
尝试这个:
excelApp.DisplayAlerts = False;
//save and close your workbook
excelApp.DisplayAlerts = True;
链接地址: http://www.djcxy.com/p/35666.html
上一篇: 互操作后,Excel实例不会关闭