9

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.

Todd Main
  • 28,951
  • 11
  • 82
  • 146
Jim G.
  • 15,141
  • 22
  • 103
  • 166

3 Answers3

14

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


        }
Gratzy
  • 9,164
  • 4
  • 30
  • 45
  • While implementing this i encountered error There is no constructor defined for Microsoft.Office.Interop.Excel.ApplicationClass type please refer to this for corrections. http://stackoverflow.com/questions/14016264/microsoft-office-interop-excel-applicationclass-has-no-constructor-defined – Desmond Oct 31 '13 at 13:04
  • 1
    I would also add `_Excel.Quit()` to finally block to close excel app. – arthur May 11 '15 at 15:58
  • 1
    Well the VB Project of the workbook remains open even after closing the workbook, any idea how to fix it? – Sujoy Apr 20 '22 at 14:05
3

A quick Google gives me this on code project:

http://www.codeproject.com/KB/office/csharp_excel.aspx

Michael Edwards
  • 6,308
  • 6
  • 44
  • 75
1

Consider using System.Diagnostics.Process to start, monitor, and close Excel. This site gives a good intro: http://www.thescarms.com/dotnet/Process.aspx, including running with an invisible window and sending input to it.

Ed Power
  • 8,310
  • 3
  • 36
  • 42