C#:Excel枚举(并关闭)所有打开的文件
我正在使用(并更改)C#中的Excel文件,如: 到目前为止,这一切都很好。我的问题是:在调试代码并取消运行而不关闭书本时,我无法使用书本。在另一次运行时打开,因为Excel和书本艺术仍然打开,因此被锁定。所以我必须通过任务管理器杀死Excel 我的想法是列举所有打开的书籍,检查文件名是否合适,然后关闭它们,如:C#:Excel枚举(并关闭)所有打开的文件,c#,excel,C#,Excel,我正在使用(并更改)C#中的Excel文件,如: 到目前为止,这一切都很好。我的问题是:在调试代码并取消运行而不关闭书本时,我无法使用书本。在另一次运行时打开,因为Excel和书本艺术仍然打开,因此被锁定。所以我必须通过任务管理器杀死Excel 我的想法是列举所有打开的书籍,检查文件名是否合适,然后关闭它们,如: foreach(Excel.Workbook b in books) { Console.WriteLine(b.ToString()); } 或 我的问题是工作簿集合总是空的,不管
foreach(Excel.Workbook b in books)
{
Console.WriteLine(b.ToString());
}
或
我的问题是工作簿集合总是空的,不管加载了哪个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();
}
可能感兴趣:谢谢你的回复。你是对的:我需要将此添加到我的代码中。但是问题仍然存在,当调试和终止应用程序内部的应用程序时,有些进程仍然存在,那么你能做些什么呢?@Werner:当我调试时,我自己关闭了任务管理器中的Excel.exe进程,就像你现在做的那样:)年,但就是这样。。。不便;-)
Excel.Application xl = null;
Excel._Workbook wb = null;
Excel._Worksheet sheet = null;
bool SaveChanges = false;
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();
}