Excel后台进程未关闭

时间:2016-04-14 21:23:08

标签: c# .net excel interop

每次打开并使用Iterop读取文件后,Excel后台进程仍保持打开状态。运行以下方法几次后,我最终得到了很多Excel后台进程。我知道在不同的时间之前已经问过这个问题但是我已经尝试了所有的建议(并在下面的代码中实现了它们)并且没有任何效果。有人可以帮忙。

    public List<double> ReadExcelFile()
    {
        Application excelApp = null;
        Workbooks workbooks = null;
        Workbook workBook = null;
        Worksheet worksheet = null;
        Range excelRange = null;
        List<double> sheetValues = new List<double>();

        try
        {
            excelApp = new Application();
            workbooks = excelApp.Workbooks;
            workBook = workbooks.Open(f_inputFilePath,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing, Type.Missing, Type.Missing,
               Type.Missing, Type.Missing);
            worksheet = workBook.Sheets["Sheet1"];
            excelRange = worksheet.UsedRange;
            object[,] sheetValuesRaw = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);

            for (int i = f_firstNumericValueIndex; i <= sheetValuesRaw.GetLength(0); i++)
                sheetValues.Add((double)sheetValuesRaw[i, 1]);
        }
        finally
        {
            workBook.Close(false, Type.Missing, Type.Missing);
            workbooks.Close();

            releaseObject(excelRange);
            releaseObject(worksheet);
            releaseObject(workbooks);
            releaseObject(workBook);

            excelApp.Quit();
            releaseObject(excelApp);
        }
        return sheetValues;
    }

    private void releaseObject(object obj)
    {
        try
        {
            Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
        }
        finally
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }

1 个答案:

答案 0 :(得分:2)

几个星期前,我在Excel互操作方面遇到了一些问题。我设法通过在try-catch-finally语句中包装使用Excel功能的方法来解决进程挂起。

所以它看起来像这样:

public List<double> MyResults() {
    try {
        return ReadExcelFile();
    }
    finally {
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

你会打电话给我的结果&#39;替代您目前所处位置的方法&#39; ReadExcelFile&#39;被召唤。

我发现通过使用Interop服务将Excel函数包装在方法之外的另一个try-catch-finally循环中,它允许Excel位超出范围并允许GC收集它们。