【问题标题】:Excel is not closing after this method使用此方法后 Excel 未关闭
【发布时间】:2018-03-25 06:11:58
【问题描述】:

使用此方法后我无法关闭 excel。我尝试使用在 StackOverflow 中找到的一些方法,但似乎无处可去。请你看看我做错了什么?谢谢!

    public void readAllFromXLS()
    {
        Excel.Application refExcel = new Excel.Application();
        Excel.Workbook refFile = refExcel.Workbooks.Open(Application.StartupPath + "\\Resources\\reference files\\price list.xlsx");
        try
        {
            string workSheet;
            if (Form1.sesion.isSRA)
                workSheet = "SRA";
            else
                workSheet = "Standard";
            Excel.Worksheet refSheet = refFile.Sheets[workSheet] as Excel.Worksheet;
            for (int row = 2; row <= refSheet.UsedRange.Rows.Count; row++)
            {
                Some Cell Reading Here...
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Marshal.FinalReleaseComObject(refSheet);

        }
        catch (Exception e)
        {
            DialogResult r = MessageBox.Show("Price List Excel File Error.", "File Read Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Exit();
            Console.WriteLine("------");
            Console.WriteLine(e);
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Marshal.FinalReleaseComObject(refFile);
        refExcel.Quit();
        Marshal.FinalReleaseComObject(refExcel);
    }

【问题讨论】:

  • 你打电话给refExcel.Quit()有什么原因之后GC.Collect
  • @MickyD,谢谢你的链接我已经看到了,我看不出我在做什么错了。
  • @mjwills 感谢您查看它,我只是在尝试不同的版本,看看它是否对我的情况有帮助。
  • 如果您想使用GC.Collect 技术,那么您肯定需要调用refExcel.Quit() 首先。然后,在调用readAllFromXLSGC.Collect(); GC.WaitForPendingFinalizers();的函数中,重复3次。

标签: c# excel com


【解决方案1】:

在他的书“.NET Development for Micorsoft Office”中。 Andrew Whitechapel 建议强制垃圾收集运行两次。

这是来自his blog的一些示例代码

if (excel != null)
{
    excel.Quit();
    excel = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

正如已经指出的,您必须在垃圾收集之前调用 Quit。

我已成功使用此技术,但现在已切换到OpenXML SDK,我发现它比 Excel 自动化要好得多。其实ClosedXML可能会更好,但我还没用过。

【讨论】:

  • 感谢 GC 的建议,从现在开始我会这样做。我讨厌 MS COM 服务,但目前我没有其他选择。问候。
猜你喜欢
  • 1970-01-01
  • 2011-10-24
  • 2021-10-13
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多