How can I get "Grand Total" vals to average rather than sum?

I am getting (gratis) a "Grand Total" column in my PivotTable:

enter image description here

For "TotalQty" and "TotalPrice" this is great, but for "AvgPrice" and "PrcntgOfTotal" not so much.

How can I get these vals to show the average in the first case rather than a sum?

the month percentages are the % of the TotalPrice for the sum of that month (not the overall sum of all months); so GrandTotal.PrcntgOfTotal should not be an average of the monthly values, either.

Here is the code that I have that generates this PivotTable:

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

Upvotes: 0

Views: 289

Answers (1)

George Grainger
George Grainger

Reputation: 172

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

Note that the DATAFIELD NUM is the index in the data field collection. Defined in:

OfficeOpenXml.Table.PivotTable.ExcelPivotTableDataFieldCollection

Upvotes: 1

Related Questions