Excel process remains open after interop; traditional method not working

后端 未结 4 1450
鱼传尺愫
鱼传尺愫 2021-01-05 02:39

I\'m running into an issue with some code I\'m debugging. Excel interop is used to extract some values from a workbook; however, Excel remains open after the program has exi

4条回答
  •  太阳男子
    2021-01-05 02:43

    This is how I got around this problem:

    // Store the Excel processes before opening.
    Process[] processesBefore = Process.GetProcessesByName("excel");
    
    // Open the file in Excel.
    Application excelApplication = new Application();
    Workbook excelWorkbook = excelApplication.Workbooks.Open(Filename);
    
    // Get Excel processes after opening the file.
    Process[] processesAfter = Process.GetProcessesByName("excel");
    
    // Now find the process id that was created, and store it.
    int processID = 0;
    foreach (Process process in processesAfter)
    {
        if (!processesBefore.Select(p => p.Id).Contains(process.Id))
        {
            processID = process.Id;
        }
    }
    
    // Do the Excel stuff
    
    // Now close the file with the COM object.
    excelWorkbook.Close();
    excelApplication.Workbooks.Close();
    excelApplication.Quit();
    
    // And now kill the process.
    if (processID != 0)
    {
        Process process = Process.GetProcessById(processID);
        process.Kill();
    }
    

提交回复
热议问题