Excel process remains open after interop; traditional method not working

后端 未结 4 1556
鱼传尺愫
鱼传尺愫 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:49

    This code works for me.

    //Declare separate object variables
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbooks xlWorkbooks = xlApp.Workbooks;
    Excel.Workbook xlWorkbook = xlWorkbooks.Add(Missing.Value);
    Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);
    
    //Create worksheet
    
    xlWorkbook.Close(false, Missing.Value, Missing.Value);
    xlWorkbooks.Close();
    xlApp.Quit();
    
    Marshal.FinalReleaseComObject(xlWorksheet);
    Marshal.FinalReleaseComObject(xlWorkbook);
    Marshal.FinalReleaseComObject(xlWorkbooks);
    Marshal.FinalReleaseComObject(xlApp);
    
    xlWorksheet = null;
    xlWorkbook = null;
    xlWorkbooks = null;
    xlApp = null;
    
    GC.Collect();
    

    This article from Microsoft has some good information regarding this issue.

提交回复
热议问题