How to determine if an Excel workbook is closed (using Interop in C #)?

I am working on a C # project that uses Microsoft.Office.Interop.Excel.Application to read values ​​from an Excel file:

 try { Application xlApp = new Application(); Workbook workbook = xlApp.Workbooks.Open(filename) // ... Load Excel values ... } finally { // ... Tidy up ... } 

In the finally block, I would like to make sure that everything is closed and disposed of properly, so nothing happens in memory and Excel closes cleanly. We saw various topics about how this code should look (more complicated than I thought!), But one may include:

 if (workbook != null) { workbook.Close(); // ... possibly also Marshal.FinalReleaseComObject(workbook); } 

However, this causes an error if the workbook is already closed, and how can I check it correctly? I would rather not just catch the error, if possible, because this type of thing distorts debugging. Is there a way to find out the state of a workbook before closing?

Another question is whether it is interesting if workbook.Close() is required, if after that xlApp.Quit(); - exit the Excel application application workbook.Close workbook.Close() (and any release of a COM object) will occur implicitly?

+4
source share
1 answer

When you open a book, the best advice is to keep track of the book and close it when necessary. If your code is sufficiently detailed, you can save a Boolean value indicating whether the file is currently open or closed.

Excel does not have a property like IsOpen. You can try to access the book:

 Workbook wbTest = xlApp.Workbooks.get_Item("some.xlsx"); 

but this creates a COM error if the book is not open, so it becomes quite dirty.

Instead, create your own IsOpen function, which returns a boolean and will go through the current open books ( Workbooks collection), checking the name using the following code:

 foreach (_Workbook wb in xlApp.Workbooks) { Console.WriteLine(wb.Name); } 

workbook.Close() not required if the workbook is saved, which reflects the normal behavior of Excel. However, all references to Excel objects must be released. As you have discovered, this is a bit difficult, and Close and Quit do not achieve this on their own.


  static bool IsOpen(string book) { foreach (_Workbook wb in xlApp.Workbooks) { if (wb.Name.Contains(book)) { return true; } } return false; } 
+2
source

Source: https://habr.com/ru/post/1494045/


All Articles