在C#中关闭一个打开的excel工作簿

时间:2014-04-09 18:39:48

标签: c# excel

我遇到了一个问题,我正在尝试修复它,因为如果程序崩溃(excel文件在后台保持打开状态),或者用户已经打开excel工作簿,程序将崩溃,因为它无法打开已打开的工作簿。

尝试使用此问题中的方法来解决此问题:C#: How can I open and close an Excel workbook?

但令我沮丧的是没有成功。

使用此设置我在wb.Close(true)收到错误,说我无法使用未分配的局部变量。对我来说这有点意义,但我不知道是怎么回事。它不像if语句,如果条件不满足则不会跳转到循环中。 try块将始终执行。

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

但是这一次,我在运行程序时在error: 80040154 Class not registered行上获得Excel.Workbook wb = new Excel.Workbook();。再说......不知道为什么。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

您希望finally代替catch。无论是否存在异常,都将始终执行finally块。即使没有抛出异常,您仍然希望关闭工作簿以清理资源。

这样的事情应该是你需要的。

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

答案 2 :(得分:0)

所以我收到了这个错误..

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;


        xlApp = new Excel.Application();
        try
        {
            xlWorkBook = xlApp.Workbooks.Open(pathexcel, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            //More code...
        }
        catch (Exception ex)
        {
            // Do any error handling you need/want to here.
        }

        range = xlWorkSheet.Range; // This is unasigned.

使用未签名的局部变量。

相关问题