0

我在数据透视表中获得(免费)一个“总计”列:

在此处输入图像描述

对于“TotalQty”和“TotalPrice”来说,这很好,但对于“AvgPrice”和“PrcntgOfTotal”来说就没有那么多了。

如何让这些 val 在第一种情况下显示平均值而不是总和?

月百分比是该月总和的 TotalPrice 百分比(不是所有月的总和);所以 GrandTotal.PrcntgOfTotal 也不应该是每月值的平均值。

这是生成此数据透视表的代码:

private void PopulatePivotTableSheet()
{
    string NORTHWEST_CORNER_OF_PIVOT_TABLE = "A6";
    AddPrePivotTableDataToPivotTableSheet();
    var dataRange = rawDataWorksheet.Cells[rawDataWorksheet.Dimension.Address];
    dataRange.AutoFitColumns();
    var pivotTable = pivotTableWorksheet.PivotTables.Add(
                        pivotTableWorksheet.Cells[NORTHWEST_CORNER_OF_PIVOT_TABLE], 
                        dataRange, 
                        "PivotTable");
    pivotTable.MultipleFieldFilters = true;
    //pivotTable.RowGrandTotals = true; <= default setting
    //pivotTable.ColumGrandTotals = true; <= default setting
    //pivotTable.RowGrandTotals = false; // this prevents the "Grand Total" column
    //pivotTable.ColumGrandTotals = false; // this prevents the totals rows at the bottom
    //pivotTable.Compact = true;
    //pivotTable.CompactData = true;
    pivotTable.GridDropZones = false;
    pivotTable.Outline = false;
    pivotTable.OutlineData = false;
    pivotTable.ShowError = true;
    pivotTable.ErrorCaption = "[error]";
    pivotTable.ShowHeaders = true;
    pivotTable.UseAutoFormatting = true;
    pivotTable.ApplyWidthHeightFormats = true;
    pivotTable.ShowDrill = true;

    // Row field[s]
    var descRowField = pivotTable.Fields["Description"];
    pivotTable.RowFields.Add(descRowField);

    // Column field[s]
    var monthYrColField = pivotTable.Fields["MonthYr"];
    pivotTable.ColumnFields.Add(monthYrColField);

    // Data field[s]
    var totQtyField = pivotTable.Fields["TotalQty"];
    pivotTable.DataFields.Add(totQtyField);

    var totPriceField = pivotTable.Fields["TotalPrice"];
    pivotTable.DataFields.Add(totPriceField);

    // Don't know how to calc these vals here, so had to put them on the data sheet
    var avgPriceField = pivotTable.Fields["AvgPrice"];
    pivotTable.DataFields.Add(avgPriceField);

    var prcntgOfTotalField = pivotTable.Fields["PrcntgOfTotal"];
    pivotTable.DataFields.Add(prcntgOfTotalField);
}
4

1 回答 1

1
pivotTable.DataFields[DATAFIELD NUM].Function =
 OfficeOpenXml.Table.PivotTable.DataFieldFunctions.Average

请注意,DATAFIELD NUM是数据字段集合中的索引。定义在:

OfficeOpenXml.Table.PivotTable.ExcelPivotTableDataFieldCollection
于 2017-08-24T15:11:58.717 回答