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

我已经在堆栈和其他网站上阅读了很多不同的主题和文章,但是在完成我的应用程序时,我仍然遇到了一些清理EXCEL Interop COMstream程的问题。

我创build了自己的一个小class,允许我加载工作表,修改单元格,重命名工作表,并格式化不同的单元格。

这里是我使用的variables和构造函数。

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

当我创build我的类对象,构造函数做到这一点:

 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来定义行和列)并使用给定的string修改它:

 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操作时,我打电话给我的清理function:

 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工作表时,我运行了清理工作,而且当我closures程序时只是为了仔细检查一切已经清理完毕。 虽然,那该死的EXCEL.EXE*32还在那里!

有了Excel(任何Office应用程序,真的)互操作性,在pipe理资源时你必须非常勤奋。 你应该总是尽可能短的时间使用资源,一旦你不再需要它们,就释放它们。 你也应该明确地释放所有对象以确保它们被正确清理。

这是我的一个更老的答案更详细: COM对象的Excel互操作性清理

如果您按照答案中列出的步骤操作,则不会有杂散的Excel实例在附近。