Excel Interop:退出Excel应用程序实例会使我的测试失败?

时间:2011-02-23 23:06:51

标签: c# .net vb.net excel excel-interop

我想封装Excel Interop的使用,以便在可重用的库中以某种方式使用它。

到目前为止,我已经编写了一些完全正常的测试,除了在每次测试之间,我强制Excel使其确实不再处理测试文件以便能够删除。

在我的每次测试之后退出应用程序实例后,Excel似乎不再响应,导致Windows显示

  

“Excel已停止工作,正在寻找解决方案”

消息。此消息持续几秒钟,同时Excel正在关闭,导致文件挂起并且我的测试抛出异常,如

  

“无法访问文件,因为它正由另一个进程使用...”

消息。否则,我的每个测试都单独运行就好了!

有关如何解决此问题的任何线索?

我是否过度使用ApplicationClass.Quit()方法?

仅在测试通过我的测试后退出Excel会导致为测试目的创建的文件不可删除。

谢谢! =)

2 个答案:

答案 0 :(得分:2)

如果您对Workbook进行了更改,则可能是“您是否希望保存更改?”正在举行的对话。在退出应用程序之前,您可以尝试将_Workbook.Saved属性设置为True。有关详细信息,请参阅here

答案 1 :(得分:1)

我有相同的“无法访问文件,因为它正被另一个进程使用...”问题。

我正在保存工作表,您需要做的是保存工作簿。这是一个完整的例子。

private void TestCreateExcel(IEnumerable<Sales1> data)
    {
        var excelApp = new Excel.Application();
        var workBook = excelApp.Workbooks.Add();
        Excel._Worksheet workSheet = excelApp.ActiveSheet;

        workSheet.Cells[1, "A"] = "Title";
        workSheet.Cells[1, "B"] = "Author(s)";
        workSheet.Cells[1, "C"] = "Release Date";
        workSheet.Cells[1, "D"] = "Total Books Sold";
        workSheet.Cells[1, "E"] = "Last 30 Days Sales";
        workSheet.Cells[1, "F"] = "Average Sales Per Month";
        workSheet.Cells[1, "G"] = "Starting Advance";
        workSheet.Cells[1, "H"] = "Current Advance";

        int index = 1; //Keep track of the which row we're writing to.
        foreach (var n in data)
        {
            index++;
            workSheet.Cells[index, "A"] = n.Title;
            workSheet.Cells[index, "B"] = n.Author;
            workSheet.Cells[index, "C"] = n.ReleaseDate.ToShortDateString();
            workSheet.Cells[index, "D"] = n.TotalBooksSold;
            workSheet.Cells[index, "E"] = n.Last30DaysSales;
            workSheet.Cells[index, "F"] = n.AverageSalesPerMonth;
            workSheet.Cells[index, "G"] = n.StartingAdvance;
            workSheet.Cells[index, "H"] = n.CurrentAdvance;
        }

        workBook.SaveAs(Server.MapPath(filePath + fileName));
        excelApp.Quit();
    }