gpt4 book ai didi

C# = 为什么 Excel 进程没有结束?

转载 作者:可可西里 更新时间:2023-11-01 08:42:41 26 4
gpt4 key购买 nike

我有以下代码:

private bool IsMousetrapFile(string path)
{

logger.Log(validateFileMessage + path);

Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Workbook xlWorkBook = workbooks.Open(path, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Sheets worksheets = (Excel.Sheets)xlWorkBook.Worksheets;
Excel.Worksheet ws = null;


foreach (string sheet in expectedWorksheets)
{

try
{

ws = (Excel.Worksheet)worksheets.get_Item(sheet);
logger.Log(validMousetrapFileMessage + path);
}
catch
{
logger.Log(validateSheetError + sheet + ": " + path);
if (ws != null)
Marshal.ReleaseComObject(ws);
Marshal.ReleaseComObject(worksheets);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(xlApp);

return false;

}

}

if (ws != null)
Marshal.ReleaseComObject(ws);
Marshal.ReleaseComObject(worksheets);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(xlApp);

return true;


}

实际上,它会检查 Excel 工作簿是否包含特定工作表。无论是否存在,我都希望 Excel 进程结束。但是,每次打开一个新工作簿时,都会添加一个新进程,并且从未删除过?

附言。我知道那里有重复的代码....它会很快被整理:)

最佳答案

当您完成处理或任何您正在做的事情时,使用 Excel.Application.Quit()

在您的情况下:xlApp.Quit();

更新:

@Lasse V. Karlsen指出了如果 Excel 已经在运行该怎么做。好吧,这是一个解决方案:(我没有测试代码,这只是给你一个想法)

private void TestMethod()
{
bool excelWasRunning = System.Diagnostics.Process.GetProcessesByName("excel").Length > 0;

// your code

if (!excelWasRunning)
{
xlApp.Quit();
}
}

关于C# = 为什么 Excel 进程没有结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5513319/

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