gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:15 27 4
gpt4 key购买 nike

当我运行以下代码时,它仍然没有释放 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com