【发布时间】:2014-12-02 10:49:46
【问题描述】:
我有一个应用程序可以从 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();
}
我错过了什么?
【问题讨论】: