C# - Proper way to open and close an excel file programmatically

前端 未结 2 1020
鱼传尺愫
鱼传尺愫 2021-02-10 01:08

I can\'t seem to find the proper way to open and close an excel file.

Here is what I have to open my file, which I find overly complicated:

        Micro         


        
相关标签:
2条回答
  • 2021-02-10 01:55

    Semi pseudo-code:

    using Excel = Microsoft.Office.Interop.Excel;
    
    # declare the application object
    Excel.Application xl = new Excel.Application();
    
    # open a file
    Excel.Workbook wb = xl.Workbooks.Open("some_file.xlsx");
    
    # do stuff ....
    
    # close the file
    wb.Close();
    
    # close the application and release resources
    xl.Quit();
    
    0 讨论(0)
  • 2021-02-10 01:56

    Release the COM objects when completed...

    using Excel = Microsoft.Office.Interop.Excel;
    using System.Runtime.InteropServices;
    
    # declare the application object
    var xl = new Excel.Application();
    
    # open a file
    var wb = xl.Workbooks.Open("some_file.xlsx");
    
    
    # close the file
    wb.Close();
    
    # close the application and release resources
    xl.Quit();
    
    #release the COM objects created as a final step:
    
    Marshal.ReleaseComObject(wb);
    Marshal.ReleaseComObject(xl);
    
    0 讨论(0)
提交回复
热议问题