C#:Excel枚举(并closures)所有打开的文件

我正在使用(和更改)来自C#的Excel文件,如:

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(); 

这工作很好迄今。 我的问题是:当debugging代码并取消运行,而不closures本书,我不能够使用books.Open在另一个运行,因为Excel和书籍艺术仍然打开,因此locking。 所以我必须通过任务pipe理器杀死Excel。

我的想法是列举所有打开的书,检查文件名是否适合并closures它们,如:

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

要么

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

我的问题是,工作簿收集总是空的,不pipe哪个Excel文件加载…任何想法如何解决这个问题?

你需要杀死Excel进程。 使用try catch块来做到这一点,如果你可以在finally块中做到这一点。

用这些 :

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

在C#中它给出:

  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(); }