【问题标题】:Getting Excel to shutdown after interop互操作后让 Excel 关闭
【发布时间】: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();
}

我错过了什么?

【问题讨论】:

    标签: c# excel com interop


    【解决方案1】:

    代码最后,你试过了吗

    app.Quit();
    

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

    【讨论】:

    • 哇,我觉得自己很笨。谢谢。
    • 不用担心,我以前也遇到过这种情况(完全相同的问题,但使用的是 Word!):)
    猜你喜欢
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    相关资源
    最近更新 更多