用c#closuresexcel的问题

我有这个代码的unit testing:

Excel.Application objExcel = new Excel.Application(); Excel.Workbook objWorkbook = (Excel.Workbook)(objExcel.Workbooks._Open(@"D:\Selenium\wszystkieSeba2.xls", true, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value)); Excel.Worksheet ws = (Excel.Worksheet)objWorkbook.Sheets[1]; Excel.Range r = ws.get_Range("A1", "I2575"); DateTime dt = DateTime.Now; Excel.Range cellData = null; Excel.Range cellKwota = null; string cellValueData = null; string cellValueKwota = null; double dataTransakcji = 0; string dzien = null; string miesiac = null; int nrOperacji = 1; int wierszPoczatkowy = 11; int pozostało = 526; cellData = r.Cells[wierszPoczatkowy, 1] as Excel.Range; cellKwota = r.Cells[wierszPoczatkowy, 6] as Excel.Range; if ((cellData != null) && (cellKwota != null)) { object valData = cellData.Value2; object valKwota = cellKwota.Value2; if ((valData != null) && (valKwota != null)) { cellValueData = valData.ToString(); dataTransakcji = Convert.ToDouble(cellValueData); Console.WriteLine("data transakcji to: " + dataTransakcji); dt = DateTime.FromOADate((double)dataTransakcji); dzien = dt.Day.ToString(); miesiac = dt.Month.ToString(); cellValueKwota = valKwota.ToString(); } } r.Cells[wierszPoczatkowy, 8] = "ok"; objWorkbook.Save(); objWorkbook.Close(true, @"C:\Documents and Settings\Administrator\Pulpit\Selenium\wszystkieSeba2.xls", true); objExcel.Quit(); 

为什么在完成testing后,我仍然有优秀的过程(它不会closures)

而且:有什么我可以改善,以更好的性能?

Excel 2007和.net 3.5

我使用这样的代码段强制closures它:

  public void DisposeExcelInstance() { //oXL.DisplayAlerts = false; //oWB.Close(null, null, null); //oXL.Quit(); //oWB.Close(null, null, null); //oXL.Quit(); ///KNG - CLEANUP code oXL.DisplayAlerts = false; oWB.Close(null, null, null); oXL.Workbooks.Close(); oXL.Quit(); if (oResizeRange != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(oResizeRange); if (oSheet != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet); if (oWB != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB); if (oXL != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL); oSheet = null; oWB = null; oXL = null; GC.Collect(); // force final cleanup! } 

也许你的引用计数是closures的: http : //support.microsoft.com/kb/317109

除了Kangkan的回答,你也可以尝试使用现有的Excel实例(如果还有一个未closures的实例在运行):

  try { objExcel = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); } catch (Exception) { if (objExcel == null) { objExcel = new Excel.Application(); } } 

尝试一些不使用Excel自动化:

如何在C#中的服务器端创buildExcel兼容的电子表格?