Closing an Excel Workbook

前端 未结 5 789
無奈伤痛
無奈伤痛 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 00:57

    Why not combine the 2. This will take care of any problems with closing before saving is complete. There is an option in the Close method to save the file.

    workbook.Close(true, fileName, Missing.Value);
    

    Also if the file is saving correctly, and your problem is purely because the excel.exe process is still running, it could be because you didn't close and release EVERYTHING needed. I have had this before and developed a more complete close down routine. My code for shutting down an excel file is:

            book.Close(true, fileName, Missing.Value); //close and save individual book
            allBooks.Close(); //close all books
            excel.Quit();
            Marshal.ReleaseComObject(allCells); //any used range objects
            Marshal.ReleaseComObject(sheet);
            Marshal.ReleaseComObject(sheets);
            Marshal.ReleaseComObject(book);
            Marshal.ReleaseComObject(allBooks);
            Marshal.ReleaseComObject(excel);
    

    This works 100% of the time for me.

提交回复
热议问题