c# - 如何在 C# 中清理 Excel 互操作对象

标签 c# excel office-interop excel-interop

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

enter image description here

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

最佳答案

您忘记保留对 ExcelObj.Workbooks 的引用并释放它:

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

关于c# - 如何在 C# 中清理 Excel 互操作对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8727290/

相关文章:

c# - Entity Framework 5 种复杂类型

c# - 如何让搜索栏输入搜索同时包含大写字母和小写字母的字符串而不更改字符串文本

c# - 使用 Excel = Microsoft.Office.Interop.Excel 编译错误

c# - 从 c# 应用程序使用插件启动 excel 应用程序

c# - Entity Framework : delete record with its sub-records

C# MongoDB FindAsync 永远不会返回 Await

Excel:通过引用另一个单元格的文本获取单元格值(不使用 VBA)

vba - 多次动态复制工作表并在 Excel 中使用 VBA 重命名

python - pandas xlsxwriter,格式表头 - 不是表头

Windows Server 2012 R2 中的 Excel Interop(插入图像)