【问题标题】:How to clean up Excel interop objects in C#如何在 C# 中清理 Excel 互操作对象
【发布时间】:2015-05-08 08:41:26
【问题描述】:

当我运行以下代码时,它仍然没有释放 excel 对象。

 public static List<string> GetExcelSheets(string FilePath)
        {
            Microsoft.Office.Interop.Excel.Application ExcelObj = null;
            Workbook theWorkbook = null;
            Sheets sheets = null;

            try
            {
                ExcelObj = new Microsoft.Office.Interop.Excel.Application();
                if (ExcelObj == null)
                {
                    MessageBox.Show("ERROR: EXCEL couldn't be started!");
                    System.Windows.Forms.Application.Exit();
                }

                theWorkbook = ExcelObj.Workbooks.Open(FilePath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
                List<string> excelSheets = new List<string>();

                sheets = theWorkbook.Worksheets;
                foreach (Worksheet item in sheets)
                {
                    excelSheets.Add(item.Name);
                }

                return excelSheets;
            }
            catch (Exception ex)
            {
                return new List<string>();
            }
            finally
            {
                // Clean up.
                releaseObject(sheets);
                releaseObject(theWorkbook);
                releaseObject(ExcelObj);
            }
        }

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

【问题讨论】:

标签: c# excel office-interop excel-interop


【解决方案1】:

您忘记保留对ExcelObj.Workbooks 的引用并发布它:

Workbooks workbooks;
...
workbooks = ExcelObj.Workbooks;
theWorkbook = workbooks.Open(...
...
releaseObject(sheets);
releaseObject(theWorkbook);
releaseObject(workbooks);
releaseObject(ExcelObj);

【讨论】:

    【解决方案2】:

    试试这个代码:

    ExcelObj.Quit();
    

    【讨论】:

    • 以后,我建议不要添加无意义的数字来填充最小长度,而是添加一个解释,无论多么简短。这也可以避免那些讨厌的 VLQ 标志。
    猜你喜欢
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多