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

时间:2010-12-13 11:10:01

标签: c# excel

我正在使用(和更改)来自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();

到目前为止,此工作正常。我的问题是:在调试代码并取消运行而没有关闭本书时,我无法使用books.Open在另一次运行,因为Excel和书籍艺术仍然打开并因此被锁定。所以我必须通过任务管理器杀死Excel。

我的想法是枚举所有打开的书籍,检查文件名是否适合并关闭它们,例如:

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

我的问题是Workbooks-Collection总是空的,无论加载哪个excel文件......有什么想法如何解决问题?

1 个答案:

答案 0 :(得分:3)

您需要终止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(); 
 }