在互操作后让Excelclosures

我有一个应用程序,从Excel电子表格中吸取一些数据。 我无法把它清理得很好。 EXCEL.EXE继续运行。 我读过其他职位,说你需要对所有的COM对象Marshal.ReleaseComObject() 。 我相信我正确地做到了这一点。

为了使事情更清洁,我已经删除了错误检查代码(与Excel没有关系),但是这是代码:

 public override MarketPriceItem[] GetMarketPrices() { string[] files = Directory.GetFiles(ConfigurationManager.AppSettings["XXSpreadsheets"]); Excel.Application app = new Excel.Application { Visible = false }; List<MarketPriceItem> prices = new List<MarketPriceItem>(); Excel.Workbooks workbooks = app.Workbooks; foreach (string filename in files) { Excel.Workbook wb = null; wb = workbooks.Open(filename); Excel.Worksheet sheet = wb.Sheets[1]; cell = sheet.Cells[1, 4]; string dateStr = cell.Text; Marshal.ReleaseComObject(cell); DateTime friday = DateTime.Parse(dateStr); DateTime today = DateTime.Today; int days = 5 - (friday - today).Days; int todayCell = (days * 2) + 1; int rows = sheet.UsedRange.Rows.Count; foreach (int key in _codeToDescription.Keys) { for (int index = 4; index < rows; index++) { cell = sheet.Cells[index, 1]; string desc = cell.Text; Marshal.ReleaseComObject(cell); if (desc.Trim() == _codeToDescription[key].Trim()) { cell = sheet.Cells[index, todayCell]; if (cell == null) { Marshal.ReleaseComObject(cell); continue; } var valVal = cell.Value; Marshal.ReleaseComObject(cell); if (valVal == null) { continue; } prices.Add(new MarketPriceItem() { MarketCode = key.ToString(), MarketDate = today, MarketTypeCode = "XX", Price = (decimal) valVal }); } } } Marshal.ReleaseComObject(sheet); Marshal.ReleaseComObject(wb); } Marshal.ReleaseComObject(workbooks); Marshal.ReleaseComObject(app); return prices.ToArray(); } 

我错过了什么?

在代码的最后,你试过了吗?

 app.Quit(); 

这应该退出正在运行的Excel的实例。