簡體   English   中英

Visual Studio Excel數據透視表不顯示數據

[英]Visual Studio Excel Pivot Table not showing data

我正在編寫一個在現有的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的事件處理程序中,用於文件創建。 該程序運行並為數據透視表創建工作表,但未列出數據值,並且我得到兩個單獨的列。 這是屏幕

請讓我知道我在做什么錯。 使用Visual Studio 2015且項目類型為Windows窗體應用程序。

替換數據透視緩存/表創建行:

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

請注意,您正在做很多多余的轉換。 通常,您不必強制轉換所有那些ivotCache和pivotfield變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM