C#: How can I open and close an Excel workbook?

Jim G. picture Jim G. · Oct 6, 2009 · Viewed 58.1k times · Source

Does anyone know how to simply open and close an Excel workbook?

I don't need to read any data from the file, I just need to open and close it. (*)

I'm guessing that I'll need to reference the Microsoft.Office.Interop.Excel assembly.


*Reason: I've already configured pivot table information with a 3rd party library (Aspose). Now I need to read the generated pivot table.

Unfortunately, the Aspose library can't generate the pivot table at runtime. It needs someone to open the file with Excel so that Excel can generate the pivot table values.

Answer

Gratzy picture Gratzy · Oct 6, 2009

after referencing Microsoft.Office.Interop.Excel also Make sure to clean up in the finally.

using Excel = Microsoft.Office.Interop.Excel;

        Excel.ApplicationClass _Excel;
        Excel.Workbook WB;
        Excel.Worksheet WS;

    try
        {

        _Excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
        WB = _Excel.Workbooks.Open("FILENAME",
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);

            //do something

        }
        catch (Exception ex)
        {
            WB.Close(false, Type.Missing, Type.Missing);

            throw;
        }
        finally
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB);

            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel);


        }