c# – Excel后台进程未关闭

每次打开并使用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();
        }
    }

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

所以它看起来像这样:

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

你可以用’MyResults’方法代替你现在调用’ReadExcelFile’的地方.

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

点赞