gpt4 book ai didi

c# - Excel 互操作 COM 不关闭

转载 作者:行者123 更新时间:2023-11-30 19:43:58 25 4
gpt4 key购买 nike

我有一些代码可以打开电子表格,读取一些值,然后关闭工作表。我需要为多个文件执行此操作。我遇到的问题是 Excel 应用程序实例没有退出,因此当我为多个文件运行我的进程时,我最终运行了几个 excel.exe 进程。有什么办法让 Excel 关闭吗?

    static void ParseFile(string file)
{
try
{
System.Console.WriteLine("parsing:" + file);
Excel.Application excel = new Excel.Application();
Excel.Workbook wb = excel.Workbooks.Open(file);
Excel.Worksheet ws = wb.Worksheets[1];
for (int i = 2; i < 27; i++)
{
log(ws.Cells[i, 1].Text);
}
wb.Close(false);
excel.Quit();
excel = null;
ws = null;
wb = null;
}
catch (Exception ex)
{
log(ex.Message);
}
}

------更新 12/11/12--------仍然保持 excel 实例打开------

static void ParseFile(string file)
{
try
{
log("parsing:" + file);
Excel.Application excel = new Excel.Application();
Excel.Workbook wb = excel.Workbooks.Open(file);
Excel.Worksheet ws = wb.Worksheets[1];
//do some stuff here
wb.Close(false);
excel.Quit();
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(ws);
Marshal.FinalReleaseComObject(wb);
Marshal.FinalReleaseComObject(excel);
excel = null;
ws = null;
wb = null;
System.GC.Collect();
}
catch (Exception ex)
{
log(ex.Message);
}
}

最佳答案

  1. 使用Marshal.FinalReleaseComObject()释放资源

  2. 如果您一个接一个地读取多个文件,那么在性能方面最好只打开/关闭 Excel 应用程序 一次并将打开/关闭应用程序部分移动到单独的函数

重构代码:

static Excel.Application OpenExcel(){
Excel.Application excel = null;
try{
excel = new Excel.Application();
return excel;
}
catch(Exception ex){
log(ex.Message);
return null;
}
}

static void ParseFile(string file)
{
try
{
System.Console.WriteLine("parsing:" + file);
Excel.Workbook wb = excel.Workbooks.Open(file);
Excel.Worksheet ws = wb.Worksheets[1];
for (int i = 2; i < 27; i++)
{
log(ws.Cells[i, 1].Text);
}
wb.Close(false);
}
catch (Exception ex)
{
log(ex.Message);
}
finally{
Marshal.FinalReleaseComObject(ws);
Marshal.FinalReleaseComObject(wb);
ws = null;
wb = null;
}
}

static void CloseExcel(Excel.Application excel){
try{
excel.Quit();
}
catch(Exception ex){
log(ex.Message);
}
finally{
Marshal.FinalReleaseComObject(excel);
excel = null;
}
}

用法:

Excel.Application excel = OpenExcel();
if(excel != null){
// Parse files in a loop
ParseFile("fileName");

// Close excel after parsing all files
CloseExcel(excel);
}

关于c# - Excel 互操作 COM 不关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13497250/

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