3

我想封装 Excel Interop 的使用,使其更容易在可重用库中使用。

到目前为止,我已经编写了一些完全运行良好的测试,除了在每个测试之间,我强制 Excel 相当,以便它不再处理测试文件以便能够删除。

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

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

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

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

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

关于如何解决这个问题的任何线索?

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

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

谢谢!=)

4

2 回答 2

2

如果您对 进行了更改,Workbook那么可能是“您希望保存更改吗?” 阻止事情的对话框。您可以尝试在退出应用程序之前将_Workbook.Saved属性设置为。True详情见这里_

于 2011-02-23T23:16:55.243 回答
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();
    }
于 2011-12-11T22:15:38.137 回答