C#EXCEL互操作问题.清理没有';不起作用

本文关键字:不起作用 互操作 问题 C#EXCEL | 更新日期: 2024-09-25 00:01:33

我在stack和其他网站上读了很多不同的线程和文章,但当我完成应用程序时,我在清理EXCEL Interop COM进程时仍然遇到一些问题。

我为自己创建了一个小类,它允许我加载工作表、修改单元格、重命名工作表以及设置不同单元格的格式。

以下是我正在使用的变量和构造函数。

Excel.Application _excelApp = null;
Excel.Workbook _excelBook = null;
Excel.Worksheet _excelSheet = null;
Excel.Range _excelRange = null;

当我创建类对象时,构造函数会这样做:

FileName = excelFileName; // Just used to reference a creation name
_excelApp = new Excel.Application();

现在,我要做的下一件事是加载一张表单进行修改:

 public bool LoadExcelSheet(string location, string file)
 {
      string startupPath = Environment.CurrentDirectory; // Get the path where the software is held
      _excelBook = _excelApp.Workbooks.Open(Path.Combine(startupPath, location, file)); // Load in the workbook
      _excelSheet = _excelBook.Worksheets[1]; // sets the excel sheet to the init worksheet
      sheetName = _excelSheet.Name; // set the sheetname variable
      isSheetLoaded = CheckIfWorkBookExists(); // a little check to see if the workbook exists - yes shows it has been loaded, if a no then it hasn't
      return isSheetLoaded;

}

我在软件中做的下一件事是运行一个函数,该函数允许我设置任何单元格(通过定义行和列的int ID),并用给定的字符串修改它:

public void ModifyCell(int row, int column, string data)
{
     int[] cellRange = new int[2] { row, column };
     _excelRange = _excelSheet.Cells;
     _excelRange.set_Item(row, column, data);
     dataFormat.Add(cellRange); // this adds each row and column into a list which holds every modified cell for easy formatting
     Marshal.ReleaseComObject(_excelRange); // Releases the COM object
}

所以,当我完成excel操作时,我会调用我的清理函数:

public void Cleanup()
{
    if (_excelApp != null) // if a cleanup hasn't been initiated
    {
                    // set all the com objects to null, this is so the GC can clean them up
                    _excelRange = null;
                    _excelSheet = null;
                    _excelBook = null;
                    _excelApp = null;
                }
                // These garbage collectors will free any unused memory - more specifically the EXCEL.EXE*32 process that LOVES to stay, forever and ever. Like a mother inlaw...
                GC.GetTotalMemory(false);
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.GetTotalMemory(true);  
    }
}

当我完成对excel工作表的修改时,我会运行清理程序,当我关闭程序时,我也会再次检查是否所有内容都已清理完毕。尽管如此,那个该死的EXCEL.EXE*32仍然存在!

C#EXCEL互操作问题.清理没有';不起作用

使用Excel(实际上是任何Office应用程序)interop,在管理资源时必须非常勤奋。你应该总是在尽可能短的时间内使用资源,并在你不再需要它们时尽快释放它们。您还应该明确释放所有对象,以确保它们被正确清理。

下面是我的一个更详细的老答案:COM对象excel interop清理

如果你按照答案中列出的步骤进行操作,你就不会留下零散的Excel实例。