我有以下代码:
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); 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进程结束.但是,每次打开新的工作簿时,都会添加一个新的进程,并且不会被删除?
PS.我知道有重复的代码在那里….它将很快整理:)
解决方法
使用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(); } }