【问题标题】:Excel sheet not closing [duplicate]Excel工作表未关闭[重复]
【发布时间】:2012-10-04 05:05:03
【问题描述】:

可能重复:
How to properly clean up Excel interop objects in C#

我有一组函数。如果该函数通过,那么我将通过一个名为 ExcelRecorder() 的函数在名为 WebServices_output.xlsx 的 Excel 表中打印一些消息 如果失败,那么我将通过 ExcelRecorder() 传递一些失败的消息

我在下面发布我的代码

public void ExcelRecorder(int error, string detailmessage, string message, int row)
        {  
            Excel.Application xlApp = new Excel.Application();                
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/WebServiceTestCases_Output.xlsx");
            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;           
                if (!string.IsNullOrEmpty(message))
                {
                    ((Range)xlWorksheet.Cells[row, "M"]).Value2 = "FAIL";
                    ((Range)xlWorksheet.Cells[row, "N"]).Value2 = error;
                    ((Range)xlWorksheet.Cells[row, "O"]).Value2 = detailmessage;
                    ((Range)xlWorksheet.Cells[row, "P"]).Value2 = message;
                }
                else
                {
                    ((Range)xlWorksheet.Cells[row, "M"]).Value2 = "PASS";
                    ((Range)xlWorksheet.Cells[row, "N"]).Value2 = "";
                    ((Range)xlWorksheet.Cells[row, "O"]).Value2 = "";
                    ((Range)xlWorksheet.Cells[row, "P"]).Value2 = "";
                }
            xlWorkbook.Save();
            xlWorkbook.Close(0,0,0);
            xlApp.Quit();
        }

虽然我特别保存我的工作簿,关闭它然后退出它,但当我打开任务管理器时,我看到 Excel.EXE 仍在运行。当我运行 ExcelRecorder() 五六次时,我在任务管理器中看到五六个 Excel.EXE,我的程序崩溃了。

这里有什么问题?为什么我添加了关闭工作簿的代码行,但工作簿没有关闭?

【问题讨论】:

  • 这是重复的,等一下,我会帮你找到的。

标签: c# .net winforms


【解决方案1】:

你需要这样做:

xlApp.Quit();

然后是这个:

System.Runtime.Marshal.ReleaseComObject(xlApp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多