使用后C#关闭Excel

时间:2014-11-17 04:05:18

标签: c# excel

我在我的应用程序中使用Excel作为Com对象。有代码示例

    public void LoadData()
    {
        LogHandler logHandler = new LogHandler(Path.GetDirectoryName(FileName) + "\\logfile.log");
        string OKATO = GetOKATOFromFileName();
        int SubjectId;
        if (!int.TryParse(OKATO, out SubjectId))
        {
            logHandler.WriteLogStr("Ошибка определения ОКАТО из имени файла (" + FileName  + ")");
            return;
        }
        int CL;
        DateTime FDate = GetDateFromFileName(out CL);
        Excel.Application excelApp = new Excel.Application();
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(FileName,
            0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
            true, false, 0, true, false, false);
        try
        {
            Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            for (int i = 1; i <= excelSheets.Count; i++)
            {
                Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(i);
                LoadDataFromSheet(excelWorksheet, SubjectId, CL, FDate);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorksheet);
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheets);
        }
        catch (Exception le)
        {
            logHandler.WriteLogStr(le.Message);
        }
        finally
        {
            excelWorkbook.Close(0);
            excelApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
        }

    }

退出void之后,我希望在此代码的情况下Excel将从内存中消失

        finally
        {
            excelWorkbook.Close(0);
            excelApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
        }

但事实并非如此。直到程序关闭Excel才存在于内存中。它只在关闭我的申请后才退出。

如何在关闭应用程序之前关闭Excel进程。

P.S。我已经阅读了这个主题Closing Excel Application Process in C# after Data Access,但这些建议都不适合我

enter image description here

1 个答案:

答案 0 :(得分:0)

处理完对象后,请使用

GC.Collect();

这就是我处理Excel对象的方式

        private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }