Closing an Excel Workbook

前端 未结 5 748
無奈伤痛
無奈伤痛 2021-01-13 00:34

I have a bit of code that opens an xls workbook;

Excel.Workbooks workBooks;
workBooks = excelApp.Workbooks;
workbook = workBooks.Open(sourceFilePath + source         


        
5条回答
  •  迷失自我
    2021-01-13 01:16

    This question keeps popping up see:

    How to properly clean up Excel interop objects in C#

    You need to call System.Runtime.InteropServices.Marshal.ReleaseComObject() on every excel object you use, even invisible ones, e.g.:

    var worksheet = excelApp.Worksheets.Open()

    There are two objects here: 1. The obvious 'Worksheet' opened with Open() 2. The "invisible" collection 'Worksheets'.

    Both of them need to be released (so you better keep a reference for Worksheets):

    var wkCol = excelApp.Worksheets;
    var worksheet = wkCol.Open();
    

提交回复
热议问题