How to terminate C# based Excel Application instance?

前端 未结 2 736
盖世英雄少女心
盖世英雄少女心 2021-01-24 19:47

I\'m working on a small code to read some Excel files. I\'ve linked the COM library for Excel 15, and am using the following code to read Excel files:

excelInsta         


        
相关标签:
2条回答
  • 2021-01-24 20:26

    Disposing the Excel COM objects can be a bit finicky. Make sure you're calling Close on your Workbook when finished, and Quit on your instance of Excel.Application.

    Release the objects by calling FinalReleaseComObject(), and for redundancy, explicitly null the COM objects:

    Runtime.InteropServices.Marshal.FinalReleaseComObject(sheet);
    Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
    Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
    
    
    sheet = null;
    workbook = null;
    app = null;
    

    Lastly, if the buggers still don't seem to go away after calling the appropriate disposal methods, explicitly releasing them, and nulling the references to the objects , call the Garbage Collector:

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

    And hopefully that will finally do it.

    Cheers.

    Edit: Also, be sure to do this in an exception handler if there's a chance your code will bomb while you're using the Interop objects, or because of them. You'll leave zombie processes even if the parent terminates.

    0 讨论(0)
  • 2021-01-24 20:27

    As per the MSDN documentation here, use the Quit() method to close your instance, as such:

    var excelInstance = new Microsoft.Office.Interop.Excel.Application()
    
    // Do stuff
    
    excelInstance.Quit();
    
    0 讨论(0)
提交回复
热议问题