Visual Studio Excel数据透视表不显示数据

时间:2015-10-18 15:55:05

标签: c# excel visual-studio pivot-table

我正在编写一个应用程序,以在现有的Excel工作簿中添加数据透视表。这是代码:

Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        if (e.Name.StartsWith("~$"))
            return;

        Excel.Application oApp;
        Excel.Worksheet oSheet;
        Excel.Workbook oBook;


        oApp = new Excel.Application();
        try
        {
            oBook = oApp.Workbooks.Open(e.FullPath);
            oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
            //Excel.Range finalCell = oSheet.Cells[2, oSheet.Rows.Count];
            Excel.Range oRange = oSheet.get_Range("A1", "M9");

            if (oApp.Application.Sheets.Count < 2)
            {
                oSheet = (Excel.Worksheet)oBook.Worksheets.Add();
            }
            else
            {
                oSheet = oApp.Worksheets[2];
            }
            oSheet.Name = "Pivot Table";
            // specify first cell for pivot table
            Excel.Range oRange2 = oSheet.Cells[3,1];

            // create Pivot Cache and Pivot Table
            Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
            Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");


            Excel.PivotField oPivotField1 = (Excel.PivotField)oPivotTable.PivotFields("Field1");
            oPivotField1.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
            oPivotField1.Position = 1;
            oPivotField1.Name = "Field1";

            Excel.PivotField oPivotField2 = (Excel.PivotField)oPivotTable.PivotFields("Field2");
            oPivotField2.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
            oPivotField2.Position = 2;
            oPivotField2.Name = "Field2";

            oBook.Save();
            Console.WriteLine("Operation Complete");
}

这是在FileSystemWatcher的文件创建事件处理程序中。该程序运行并创建数据透视表的工作表,但没有列出数据值,我也得到两个单独的列。 Here's the screen

请让我知道我做错了什么。使用Visual Studio 2015和项目类型是Windows窗体应用程序。

1 个答案:

答案 0 :(得分:1)

替换数据透视缓存/表格创建行:

Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");

PivotCache oPivotCache = oBook.PivotCaches().Create(XlPivotTableSourceType.xlDatabase, oRange, XlPivotTableVersionList.xlPivotTableVersion14);
PivotTable oPivotTable = oPivotCache.CreatePivotTable(TableDestination: oRange2, TableName: "Summary");

请注意,您正在进行大量冗余投射。您通常不必投射所有的pivotCache和pivotfield变量。