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

2019-01-20 10:33发布

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.

3条回答
欢心
2楼-- · 2019-01-20 10:42

A quick Google gives me this on code project:

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

查看更多
Viruses.
3楼-- · 2019-01-20 10:52

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.

查看更多
老娘就宠你
4楼-- · 2019-01-20 11:00

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


        }
查看更多
登录 后发表回答