创建并编辑Excel文件后释放

本文关键字:释放 文件 Excel 编辑 创建 | 更新日期: 2023-09-27 18:04:41

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

下面是我的代码:
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();
    }
} 

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

创建并编辑Excel文件后释放

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

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

我发现这个链接是一个伟大的资源,当我做Excel互操作如何正确清理Excel互操作对象?

 finally
{
    GC.Collect(); 
   GC.WaitForPendingFinalizers();
}

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

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

xlApp = null;
xlWorkBook = null;

这能解决问题吗?

我有同样的问题,但我修复了它。因此,在我创建文件之后,我关闭了它。

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