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

I cannot find a suitable way to open and close the excel file.

Here's what I need to open for my file, which I find too complex:

        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
            0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
            true, false, 0, true, false, false);
        Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;

        Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)excelApp.Worksheets[2];
        sheet.Select(Type.Missing);

      

I have no idea how to close it properly. I need to save it with the same path and make sure excel is not running in the background yet after closing it.

Can someone make it easier for me? Thanks to

+3


source to share


2 answers


Semi-pseudocode:



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();

      

+2


source


Release COM objects when finished ...



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);

      

+3


source







All Articles