简体   繁体   中英

C# Interop not closing Excel process after execution

I have the following blocks of code:

    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(this.pathToFile);
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    Excel.Range xlRange = xlWorksheet.UsedRange;

I push the xlRange into an array using:

someArray = (System.Object[,])xlRange.Value2;

Afterwards I try to cleanup with:

    Marshal.ReleaseComObject(xlRange);
    Marshal.ReleaseComObject(xlWorksheet);

    xlWorkbook.Close();
    Marshal.ReleaseComObject(xlWorkbook);
    xlApp.Quit();
    Marshal.ReleaseComObject(xlApp);

However, even with all four of the excel objects being released with Marshal , the process stays open and prevents the file from being opened again.

Any ideas as to how to properly clean up Interop excel objects?

I had a similar issue and managed to close the application following this processs;

GC.Collect();
GC.WaitForPendingFinalizers();

Marshal.FinalReleaseComObject(xlRange);
Marshal.FinalReleaseComObject(xlWorksheet);

xlWorkbook.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlWorkbook);

xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM