C#:如何打开和关闭Excel工作簿?

Jim*_* G. 7 c# excel office-interop aspose

有谁知道如何简单地打开和关闭Excel工作簿?

我不需要从文件中读取任何数据,我只需要打开并关闭它.(*)

我猜我需要引用Microsoft.Office.Interop.Excel程序集.


*原因:我已经使用第三方库(Aspose)配置了数据透视表信息.现在我需要阅读生成的数据透视表.

不幸的是,Aspose库无法在运行时生成数据透视表.它需要有人用Excel打开文件,以便Excel可以生成数据透视表值.

Gra*_*tzy 12

在引用Microsoft.Office.Interop.Excel之后还要确保在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);


        }
Run Code Online (Sandbox Code Playgroud)