Excel interop COM doesn't close

前端 未结 4 584
青春惊慌失措
青春惊慌失措 2021-01-22 03:27

I have some code that opens a spreadsheet, reads some values, and then closes the sheet. I need to do this for multiple files. The problem I\'m having is that the Excel applic

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-22 04:03

    I wanted to share some of my experiences with respect to this same problem.

    I re-structured my Excel Interop code to ensure I never have more than one property period, following the "rules" stated within this webpage: http://jake.ginnivan.net/vsto-com-interop/

    Ex:

    • I removed strings like the following...

    ExcelApplication.ExcelWorkbook.Workbookworksheet.WorksheetRange.Range.Count

    (exaggerated a bit).

    -I replaced such strings with items like the following...

    var CurrentRange = currentMDL.CurrentMDL_xlRange;
    var CurrentRangeColumns = CurrentRange.Columns;
    var CurrentRangeWorksheet = currentMDL.CurrentMDL_Worksheet;
    var CurrentRangeWorksheetCells = CurrentRangeWorksheet.Cells;
    

    From here, I am able to tap into what I want much more cleanly.

    Ex:

    for(int i = 1; i <= CurrentRangeColumns.Count; i++)
    {
    //Doing stuff
    }
    

    I made sure to close my Excel document within the same method in which it was opened, after all of my operations took place. I plan on re-visiting this to see if i am able to close the Excel documents remotely.

    Lastly, I made sure to follow up with some releases of all my COM objects used within my Excel handling methods.

    Ex:

    Marshal.FinalReleaseComObject(CurrentRange);
    Marshal.FinalReleaseComObject(CurrentRangeCells);
    Marshal.FinalReleaseComObject(CurrentRangeRows);
    

    The order of operations matter here. I made sure to close my workbook, then Excel application, then finally released my COM objects. I spoke with an engineer I work with, regarding the usage of ComObject release. He says that I shouldn't need to use those calls, because garbage collection should eventually clean up my mess. With my studies here, I could not get garbage collection to close out my instances of Excel and opted to release them myself.

    -Chris

提交回复
热议问题