互操作后让Excel关闭

时间:2014-10-07 21:31:29

标签: c# excel com interop

我有一个应用程序从Excel电子表格中提取一些数据。我不能很好地清理它。 EXCEL.EXE继续运行。我已经阅读了其他帖子,说你需要Marshal.ReleaseComObject()所有COM对象。我相信我这样做是正确的。

为了让事情变得更清洁,我删除了错误检查代码(没有与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();
}

我错过了什么?

1 个答案:

答案 0 :(得分:2)

在代码的最后,你试过吗

app.Quit();

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