【问题标题】:Releasing Excel file after creating and editing it创建和编辑后释放 Excel 文件
【发布时间】:2020-07-08 16:46:45
【问题描述】:

我正在创建一个可以从数据库数据生成 Excel 文件的 Windows 窗体应用程序。将数据库填充到文件中后,我打开它并执行一个宏,保存文件然后关闭它(或者我认为我正在关闭它)。这些文件保存在我的 HDD 上,但是当所有文件生成后,我必须能够生成一组新文件,因此我必须在生成新文件之前从我的 HDD 中删除所有旧文件。在运行应用程序一次并尝试生成新的文件集后,我收到一条错误消息,指出其中一个文件(第一批中生成的最后一个文件)被另一个进程使用。

这是我的代码:

public void RemoveRows_Macro(string fileName)
{

    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
    xlWorkBook = xlApp.Workbooks.Open(fileName);
    //xlApp.Visible = true;
    xlApp.DisplayAlerts = true;

    //Run the macro
    xlApp.Run("RemoveRows", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    xlWorkBook.Save();

    xlWorkBook.Close(false);
    xlApp.Quit();
    releaseObject(xlApp);
    releaseObject(xlWorkBook);
}

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error in releasing object :" + ex);
        obj = null;
    }
    finally
    {
        GC.Collect();
    }
} 

由于应用程序没有释放文件,我做错了什么?

【问题讨论】:

    标签: c# .net office-interop


    【解决方案1】:

    您可能希望先释放对象,然后按照分配它们的相反顺序将它们设置为 null。

    releaseObject(xlWorkBook);
    releaseObject(xlApp);
    xlWorkBook = null;
    xlApp = null;
    

    我在进行 Excel 互操作时发现此链接是一个很好的资源 How do I properly clean up Excel interop objects?

    【讨论】:

    • 感谢您的链接。感谢帮助
    【解决方案2】:
     finally
    {
        GC.Collect(); 
       GC.WaitForPendingFinalizers();
    }
    

    【讨论】:

    • 对不起,我打错了!我现在试试。
    【解决方案3】:

    我现在无法运行测试,但看起来您在将 xlApp 和 xlWorkBook 传递给 releaseObject 之前将它们设置为 null。之后可能还有其他原因。

    【讨论】:

    • 我已经删除了 2 行,它仍然没有释放最后生成的文件。
    【解决方案4】:

    您首先将 xlApp 和 xlWorkBook 设置为 null,然后尝试释放它。尝试注释掉这两行:

    xlApp = null;
    xlWorkBook = null;
    

    这能解决问题吗?

    【讨论】:

    • 马上试过了。它没有解决问题。它仍然锁定最后生成的文件
    【解决方案5】:

    我遇到了同样的问题,但我已经解决了。因此,在创建文件后,我将其关闭。

    xlWorkbook.SaveAs("nameExcel");
    xlWorkbook.Close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-27
      • 2011-03-09
      • 2013-03-28
      • 1970-01-01
      • 2022-07-08
      • 2012-03-08
      • 2015-10-24
      • 2016-05-23
      相关资源
      最近更新 更多