繁体   English   中英

C#使用后关闭Excel

[英]C# closing Excel after using

我在应用程序中使用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进程。

ps我已经阅读了本主题,在数据访问后在C#中关闭Excel应用程序进程,但是没有任何建议对我有用

在此处输入图片说明

处理完对象后,请使用

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();
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM