C#EXCEL互操作问题。清理工作不起作用

时间:2015-03-03 15:18:53

标签: c# excel com

我已经在堆栈和其他网站上阅读了很多不同的主题和文章,但是当我完成我的应用程序时,我仍然有一些问题需要清理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仍然存在!

1 个答案:

答案 0 :(得分:1)

使用Excel(任何Office应用程序,实际上)互操作,您在管理资源时必须非常勤奋。您应该始终尽可能短的时间使用资源,并在您不再需要它们时立即释放它们。您还应该明确地释放所有对象,以确保它们能够正确清理。

这是我的一个较旧的答案,更详细:COM object excel interop clean up

如果您按照答案中列出的步骤操作,那么您将无法使用流浪的Excel实例。