Excel Interop: Exiting an instance of an Excel application makes my tests fail?

I want to encapsulate the use of Excel Interop to make it easier to use in a reusable library.

So far I have written several tests that work well, except that between each test I force Excel to have no descriptor for the test file in order to be able to delete.

As soon as I exit the application instance after each of my tests, Excel seems to no longer respond, causing Windows to display

"Excel stops working and looking for a solution"

message. This message lasts several seconds while Excel closes, causing the file to freeze, and my tests throw an exception, for example

"Cannot access the file because it is being used by another process ..."

message. Otherwise, each of my tests is individually performed just fine!

Is there a key to solving this problem?

Am I abusing the method ApplicationClass.Quit()?

Exiting Excel only after testing using my tests leads to the fact that files created for testing purposes cannot be deleted.

Thank! =)

+3
source share
2 answers

If you made changes to Workbook, it could be "Do you want to save the changes?" a dialogue that keeps things up. You can try setting the property _Workbook.Savedto Truebefore exiting the application. See here for more details .

+2

" , ...".

, , . .

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

Source: https://habr.com/ru/post/1794281/


All Articles