Home » excel » C#: Excel enum (and close) all open files

C#: Excel enum (and close) all open files

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m using (and changing) an Excel-File from C#, like:

    Excel.Application app = new Excel.Application();
    Excel.Workbooks books = exel_app.Workbooks;
    Excel.Workbook book = books.Open(sFileName, 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);

... changing some things in the Excel-File ...

book.Close(true, Type.Missing, Type.Missing);
app.Quit();

This works fine so far. My problem is: When debugging the code and cancel the run without the book being closed, I’m not able to use books.Open on another run, because Excel and the book art still open and therefore locked. So I have to kill Excel via the task-manager.

My idea was to enumerate through all open books, check if the filename fits and close them, like:

foreach(Excel.Workbook b in books)
{
Console.WriteLine(b.ToString());
}

or

Excel.Workbook bookOld = books.get_Item(sFileName);
if (bookOld != null) bookOld.Close(false, Type.Missing, Type.Missing);

My problem is that the Workbooks-Collection is always empty, no matter which excel-files are loaded… Any idea how to solve the problem?

How to&Answers:

You need to kill the Excel processes.
Use a try catch block to do this, and i f you can do it in a finally block.

With these :

   Excel.Application xl = null;
   Excel._Workbook wb = null;
   Excel._Worksheet sheet = null;
   bool SaveChanges = false;

In C# it gives :

 finally
 {

   try
   {
     xl.Visible = false;
     xl.UserControl = false;
     // Close the document and avoid user prompts to save if our
     // method failed.
     wb.Close(SaveChanges,null,null);
     xl.Workbooks.Close();
   }
   catch { }

   // Gracefully exit out and destroy all COM objects to avoid hanging instances
   // of Excel.exe whether our method failed or not.

   xl.Quit();

   if (sheet !=null)   { Marshal.ReleaseComObject (sheet); }
   if (wb !=null)      { Marshal.ReleaseComObject (wb); }
   if (xl !=null)      { Marshal.ReleaseComObject (xl); }

    sheet=null;
    wb=null;
    xl = null;
    GC.Collect(); 
 }