Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 741
Jim G. Avatar asked Oct 06 '09 16:10

Jim G.


3 Answers

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


        }
like image 106
Gratzy Avatar answered Nov 17 '22 23:11

Gratzy


A quick Google gives me this on code project:

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

like image 26
Michael Edwards Avatar answered Nov 18 '22 00:11

Michael Edwards


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.

like image 1
Ed Power Avatar answered Nov 17 '22 23:11

Ed Power