在C#中关闭一个开放的excel工作簿 [英] Closing an open excel workbook in C#
问题描述
我有一个问题,我正在修复它,因为如果程序崩溃(excel文件在后台保持打开状态),或者用户已经打开了excel工作簿已经打开程序将崩溃,因为它无法打开一个已经打开的工作簿。
There is one issue that I have been having, and I am trying to fix it because if the program crashes (the excel file stays open in the background), or the user has the excel workbook already open the program will crash because it is unable to open an already opened workbook.
尝试通过使用此问题的方法来解决此问题: C#:如何打开和关闭Excel工作簿?
Was trying to counter this issue by using the method from this question : C#: How can I open and close an Excel workbook?
但令我失望的是没有成功。
But much to my dismay no success.
使用此设置,我在中收到错误wb.Close(true )
说我不能使用未分配的局部变量。对我来说这是有道理的,但我看不出如何。如果语句不符合,那么如果不符合条件,则不会在循环中跳转。
try
块将始终执行。
With this setup I get an error at wb.Close(true)
saying I cannot use an unassigned local variable. To me it kind of makes sense, but I don't see how that is the case. It's not like an if
statement where if the condition isn't met it doesn't jump in the loop. The try
block will always execute.
Excel.Workbook wb;
try
{
wb = exApp.Workbooks.Open(@file);
}
catch (Exception)
{
wb.Close(true);
}
我也试过这样:
Excel.Workbook wb = new Excel.Workbook();
try
{
wb = exApp.Workbooks.Open(@file);
}
catch (Exception)
{
wb.Close(true);
}
但这一次,我得到一个错误:80040154课程没有注册
行 Excel.Workbook wb = new Excel.Workbook();
在运行程序时。再次...不知道为什么。
but this time, I get a error: 80040154 Class not registered
on the line Excel.Workbook wb = new Excel.Workbook();
when running the program. again... don't know why.
非常感谢任何帮助。
推荐答案
尝试这样:
Excel.Workbook wb = null;
try
{
wb = exApp.Workbooks.Open(@file);
}
catch (Exception)
{
if (wb != null) wb.Close(true);
}
这篇关于在C#中关闭一个开放的excel工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!