Excel Interop:退出Excel应用程序实例会使testing失败?

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

到目前为止,我已经写了一些testing,一起运行良好,除了在每个testing之间,我强迫Excel,以便它不必处理testing文件,以便能够删除。

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

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

信息。 此消息持续几秒钟,同时Excel正在closures,导致文件挂起发生,我的testing抛出一个exception

“由于正被另一个进程使用而无法访问文件…”

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

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

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

只有在testing完成后才退出Excel,导致为testing创build的文件不能被删除。

谢谢! =)

如果您对Workbook进行了更改,那么是否可以是“您是否希望保存更改?” 对话框正在举办。 您可以尝试在退出应用程序之前将_Workbook.Saved属性设置为True 。 详情请看这里

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

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

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