Closing an open excel workbook in C#

2019-09-09 16:43发布

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.

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.

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

I also tried this way :

Excel.Workbook wb = new Excel.Workbook();
try
{
    wb = exApp.Workbooks.Open(@file);
}
catch (Exception)
{
    wb.Close(true);
}

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.

Any help is greatly appreciated.

标签: c# excel
2条回答
小情绪 Triste *
2楼-- · 2019-09-09 16:50

Try this:

Excel.Workbook wb = null;
try
{
    wb = exApp.Workbooks.Open(@file);
}
catch (Exception)
{
    if (wb != null) wb.Close(true);
}
查看更多
欢心
3楼-- · 2019-09-09 17:12

You want finally instead of catch. A finally block will always execute, whether there is an exception or not. Even if there isn't an Exception thrown, you still want to close the workbook to clear up the resources.

Something like this should be what you need.

Excel.Workbook wb = new Excel.Workbook();

try {
    wb = exApp.Workbooks.Open(@file);
    //More code...
}
catch (Exception ex) {
    // Do any error handling you need/want to here.
}
finally {
    // If there's a way to determine if the workbook is open, try that first.
    wb.Close(true);
}
查看更多
登录 后发表回答