2010-12-13 64 views
1

我使用(并改变)从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); 

我的问题是,该工作簿,收藏是永远空,无论哪个excel文件加载...任何想法如何解决这个问题?

+0

可能感兴趣的:http://www.devasp.net/net/articles/display/688.html – Fionnuala 2010-12-13 11:26:05

回答

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

感谢您的回复。你是对的:我需要把它添加到我的代码中。但问题仍然存在,当在应用程序内部调试和终止应用程序时,有些进程存在 - 那么您可以对此做些什么? – Werner 2010-12-13 11:53:34

+0

@Werner:当我正在调试时,我正在自己关闭任务管理器中的Excel.exe进程,就像你现在正在做的那样:) – LaGrandMere 2010-12-13 12:54:18

+0

年,但那样...不方便;-) – Werner 2010-12-16 09:17:01