Technical Article

Pivot Show Values As in Delphi: Rank and Running Total

A generated sales workbook has a pivot column titled "Rank by Region", and the Hardware row reads 1, 1 and 2 for amounts of 30, 30 and 20. A user opens the file, clicks Refresh, and the same three cells now read 30, 30 and 20. The cached numbers were right all along. What broke was a GUID: the rank mode lives in an extension block identified by {E15A36E0-9728-4e99-A89B-3F7291B0FE68}, a packaging step uppercased it to 4E99, and Excel compares that identifier case-sensitively when it rebuilds the pivot

The GUID is only one of the things a generated "Show Values As" column has to get right. The Excel menu never spells out how tied values rank, what a running percentage means over an average, or why one comparison column can hold blanks, #NULL! and #DIV/0! side by side

One Excel menu, two places in the file

HotXLS models the menu with two properties on TXLSPivotDataField, because the XLSX format stores it in two places. The modes Excel 2007 shipped with sit in the showDataAs attribute of the dataField element inside pivotTableDefinition, using the ECMA-376 ST_ShowDataAs enumeration. Excel 2010 added rank and the parent and cumulative percentages, which had no slot in that enumeration, so they were written as an x14:dataField element with a pivotShowAs attribute, wrapped in an extLst block on the same data field

ShowDataAs takes a TXLSPivotShowDataAs value: xlpsdaNormal, xlpsdaDifference, xlpsdaPercent, xlpsdaPercentDiff, xlpsdaRunTotal, xlpsdaPercentOfRow, xlpsdaPercentOfCol, xlpsdaPercentOfTotal or xlpsdaIndex. ExtendedShowDataAs takes a TXLSPivotExtendedShowDataAs value: xlpesdaPercentOfParent, xlpesdaPercentOfParentRow, xlpesdaPercentOfParentColumn, xlpesdaPercentOfRunningTotal, xlpesdaRankAscending or xlpesdaRankDescending, with xlpesdaNone meaning no extended mode

HotXLS pivot ShowDataAs and ExtendedShowDataAs mapping to dataField showDataAs and x14 pivotShowAs XML in Delphi
HotXLS mirrors the Excel Show Values As menu with two mutually exclusive properties: ShowDataAs for the classic ECMA-376 modes and ExtendedShowDataAs for the x14 pivotShowAs extension

A data field uses one group or the other. If ShowDataAs is anything other than xlpsdaNormal while ExtendedShowDataAs is anything other than xlpesdaNone, TXLSXWorkbook.MaterializeNativePivotTable returns -1 and leaves the sheet as it was, previous cells and pivot bounds included. Saving the same field raises ERangeError with the message "Pivot basic and extended display modes are mutually exclusive". Out-of-range enum values get the same treatment: both the lower and the upper bound are checked, since a stray byte of 255 cast into a Delphi enum can come back as -1 and slip past an upper-bound test

BaseField and BaseItem name the comparison target. BaseField is a zero-based position in the pivot table's own field list, and it is read by difference, percent of, percent difference, running total, percent of parent, running total percent and both rank modes. BaseItem is a zero-based item position inside that field, or xlPivotBaseItemPrevious / xlPivotBaseItemNext for "compared with the neighbor", and only the three comparison modes read it. Parent row and parent column percentages take neither: they divide by the row or column one level up, whatever BaseField says

Building a ranked pivot in Delphi

The working sequence is build the pivot, set the display mode on the data field, then call MaterializeNativePivotTable before saving so the sheet holds the grid Excel would compute. The example ranks each category's regional amounts in descending order, so the largest amount in a row gets rank 1

program RegionRank;

uses
  SysUtils, lxHandleX, lxPivot;

// Reader-side helper, not part of HotXLS: BaseField wants the position in
// the pivot's field list, so look it up instead of hard-coding a number
function PivotFieldIndex(Pivot: TXLSPivotTable; Field: TXLSPivotField): Integer;
var
  I: Integer;
begin
  for I := 0 to Pivot.FieldCount - 1 do
    if Pivot.Fields[I] = Field then
      Exit(I);
  Result := -1;
end;

procedure PutRow(Sheet: TXLSXWorksheet; Row: Integer;
  const Category, Region: string; Amount: Integer);
begin
  Sheet.Cells[Row, 1].Value := Category;
  Sheet.Cells[Row, 2].Value := Region;
  Sheet.Cells[Row, 3].Value := Amount;
end;

var
  Book: TXLSXWorkbook;
  Data, Report: TXLSXWorksheet;
  Pivot: TXLSPivotTable;
  Region: TXLSPivotField;
  Measure: TXLSPivotDataField;
begin
  Book := TXLSXWorkbook.Create;
  try
    Data := Book.Sheets.Add('Data');
    Data.Cells[1, 1].Value := 'Category';
    Data.Cells[1, 2].Value := 'Region';
    Data.Cells[1, 3].Value := 'Amount';
    PutRow(Data, 2, 'Hardware', 'East', 30);
    PutRow(Data, 3, 'Hardware', 'North', 30);
    PutRow(Data, 4, 'Hardware', 'West', 20);
    PutRow(Data, 5, 'Software', 'East', 12);
    PutRow(Data, 6, 'Software', 'North', 45);
    PutRow(Data, 7, 'Software', 'West', 18);

    Report := Book.Sheets.Add('Report');
    Pivot := Report.AddPivotTable('Data!A1:C7', 4, 3, 'RegionRank');
    if Pivot = nil then
      raise Exception.Create('Source range was rejected');
    Pivot.AddRowField('Category');
    Region := Pivot.AddColumnField('Region');
    Measure := Pivot.AddDataFieldByName('Amount', xlpaSum);
    Measure.DisplayName := 'Rank by Region';

    Measure.ShowDataAs := xlpsdaNormal;            // keep the basic mode off
    Measure.ExtendedShowDataAs := xlpesdaRankDescending;
    Measure.BaseField := PivotFieldIndex(Pivot, Region);

    if Book.MaterializeNativePivotTable(Pivot) <> 1 then
      raise Exception.Create('Pivot display mode was rejected');
    if Book.SaveAs('region-rank.xlsx') <> 1 then
      raise Exception.Create('Save failed');
  finally
    Book.Free;
  end;
end.

Expected: the Hardware row shows 1, 1 and 2 under East, North and West, the Software row shows 3, 1 and 2, and the grand total column on the right stays empty, because the axis a rank walks has no rank to show in its own total

The explicit ShowDataAs := xlpsdaNormal is redundant on a field created a few lines earlier. Keep it anyway. Code like this gets copied into routines that edit pivots loaded from customer workbooks, where the data field may already carry a basic mode, and then that line is what keeps the call from returning -1. Check the return value for a related reason: a rejected materialization leaves the old grid in place, and an unchecked call ships a file whose cells describe the previous configuration

BaseField reaches the file even if MaterializeNativePivotTable is never called. The writer emits the baseField attribute for percent of parent, running total percent and both rank modes as soon as the extended mode is set, so a workbook saved straight after configuration still tells Excel which field to rank across when someone refreshes it

Why does a rank column turn into sums after Refresh?

Excel recognizes the pivotShowAs extension only when its uri attribute matches {E15A36E0-9728-4e99-A89B-3F7291B0FE68} exactly, lowercase e in 4e99 included. GUIDs are case-insensitive almost everywhere else, and plenty of XML tooling normalizes them to uppercase. A file with 4E99 opens without a repair prompt and with every cached cell correct, because on open Excel paints the stored values. RefreshTable is different: it re-reads the definition, skips the extension it does not recognize, and recomputes the column as the plain aggregate

HotXLS pivot x14 pivotShowAs URI casing 4e99 versus 4E99 with rank column lost to plain sum after Excel refresh
Excel matches the x14 pivotShowAs extension URI case-sensitively, so a GUID uppercased downstream opens normally yet loses the rank mode at the first RefreshTable

HotXLS writes the URI in the casing Excel expects. When MaterializeNativePivotTable restages a data field from a loaded workbook, it finds the existing extension regardless of case and writes the uri back in the exact form, so re-materializing a pivot repairs an uppercased identifier rather than carrying it forward. The remaining exposure is whatever touches the package after SaveAs: a signing step, a GUID-normalizing post-processor, a script that rebuilds extLst elements

The check that catches it costs one click. Open the generated file in Excel, refresh the pivot, and compare the extended column against the ranks or percentages you expect. Reading cached cells with any library proves nothing here, since those cells are correct in the broken file too

How does Excel rank ties and order running totals?

Pivot rank in Excel is a dense rank, and MaterializeNativePivotTable produces the same numbers. Amounts of 30, 30 and 20 rank 1, 1 and 2: a tie counts as one distinct value ahead of you. The worksheet function RANK.EQ uses competition ranking and returns 1, 1 and 3 for the same amounts, and no pivot display mode reproduces that. When a report needs competition ranks, compute them in the source data or in a formula column next to the pivot; trying to post-process the pivot cells is the worse choice, because the next refresh puts the dense ranks back

HotXLS pivot dense rank ties 30 30 20 as 1 1 2 versus RANK.EQ competition 1 1 3 in Delphi
HotXLS follows Excel's dense pivot rank, so tied amounts of 30 and 30 both rank 1 and the next distinct amount ranks 2 instead of the competition ranking 3

Running totals, running total percentages and previous or next comparisons walk the members in the order they are displayed. Setting SortType changes that order while the field's item list keeps its original sequence, so a calculation that walks the item list gives plausible numbers that disagree with Excel after refresh. The fragment below sorts Category descending and adds two measures that depend on the order

var
  Category: TXLSPivotField;
  Growth, Running: TXLSPivotDataField;
...
Category := Pivot.AddRowField('Category');
Category.SortType := xlpfstDescending;        // Software above Hardware
Pivot.AddColumnField('Region');

Growth := Pivot.AddDataFieldByName('Amount', xlpaSum);
Growth.DisplayName := 'Change vs previous';
Growth.ShowDataAs := xlpsdaPercentDiff;
Growth.BaseField := PivotFieldIndex(Pivot, Category);
Growth.BaseItem := xlPivotBaseItemPrevious;  // the row displayed above

Running := Pivot.AddDataFieldByName('Amount', xlpaSum);
Running.DisplayName := 'Running amount';
Running.ShowDataAs := xlpsdaRunTotal;
Running.BaseField := PivotFieldIndex(Pivot, Category);

if Book.MaterializeNativePivotTable(Pivot) <> 1 then
  raise Exception.Create('Pivot display mode was rejected');

Expected with the six rows from the first example: Software is displayed first, so its "Change vs previous" cells are empty, and its running amounts are simply 12, 45 and 18. Hardware comes second; its East change is (30 - 12) / 12 = 1.5, North is (30 - 45) / 45 ≈ -0.333, West is (20 - 18) / 18 ≈ 0.111, and its running amounts are 42, 75 and 38. Under the default ascending order the two rows swap roles

The empty cells at the top edge are deliberate. With no previous member, difference and percent difference leave the cell blank, and only plain percent of (xlpsdaPercent) compares the edge member with itself and shows 1. Software's three "Change vs previous" cells in the example above stay empty for that reason, while a percent-of column with Previous as its base would show 1 in all three

Why can a cumulative percentage exceed 100 percent?

Running total percent (xlpesdaPercentOfRunningTotal) over an average can end well above 100 percent, and that is Excel's result too. Excel accumulates the displayed member aggregates and divides by an aggregate that, for averages, is not their sum. For sums both are the same number, so the last member lands on exactly 100 percent and nobody notices the rule

Suppose a pivot averages order size per category, the three categories average 10, 20 and 30, each has the same number of source rows, and Category is the innermost row field and the base field. The divisor is the overall average, 20. The running percentages come out as 10 / 20 = 50 percent, 30 / 20 = 150 percent and 60 / 20 = 300 percent. HotXLS writes those values as they are. Clamping the last one to 100 percent would produce a cell that disagrees with the same file after a refresh

The divisor depends on where the base field sits. As the innermost field on its axis, the divisor is the original aggregate for that axis position, which is the overall average in the example. As an outer field in a nested layout, the divisor is the sum of the displayed aggregates across the matching members. A layout change can move the base field between those two positions without anyone touching BaseField, so the same configuration can produce different last-row percentages in two report layouts

Percent of row, percent of column and percent of grand total divide by the original aggregate at that scope, averages included. A percent of total over averages is the cell average divided by the overall average, so a column of them need not add up to 100 percent

Blanks, #NULL! and #DIV/0! in comparison modes

Percent-of-base comparisons (xlpsdaPercent and xlpsdaPercentDiff) produce three different empty results, and the materialized grid keeps them apart the way Excel does:

  • No source rows at the base item's intersection: the cell is blank
  • The base item has data but the cell's own intersection has none: the cell holds #NULL!
  • The base item exists and its aggregate is zero: the cell holds #DIV/0!

Code that reads values back from the report sheet should test with VarIsEmpty and VarIsError before treating a cell as a number. Percent of row, column and total are more forgiving, since a missing numerator counts as zero there. Parent row and parent column percentages are blank when the pivot has no field on the corresponding axis, as there is no parent to divide by. Totals along the axis that a comparison, running total or rank walks are blank too, so a total row full of empty cells under a running total is the correct output

Switching modes on an imported pivot

Changing the display mode of a pivot that came from an existing workbook uses the same properties plus the second MaterializeNativePivotTable overload. Passing True as AAdoptExisting lets the call take over the cells Excel already wrote for that pivot; without it, the call refuses to overwrite results it did not produce

Book := TXLSXWorkbook.Create;
try
  if Book.Open('quarterly-sales.xlsx') <> 1 then
    raise Exception.Create('Cannot open workbook');
  Pivot := Book.Sheets.SheetByName('Sales').PivotTables.FindByName('SalesPivot');
  if Pivot = nil then
    raise Exception.Create('Pivot not found');

  with Pivot.DataFields[0] do
  begin
    ShowDataAs := xlpsdaNormal;                      // clear any basic mode
    ExtendedShowDataAs := xlpesdaPercentOfParentRow; // no BaseField needed
  end;

  if Book.MaterializeNativePivotTable(Pivot, True) <> 1 then
    raise Exception.Create('Could not re-materialize the pivot');
  Book.SaveAs('quarterly-sales-share.xlsx');
finally
  Book.Free;
end;

When the mode changes, the staged definition drops the attributes that no longer apply, showDataAs, pivotShowAs, baseField and baseItem alike, so the saved file never carries a stale basic mode next to a new extended one. The same step keeps the compact and outline flags on measure and inactive fields in line with the report layout. Excel builds refreshed data captions from those flags as well as from the row and column fields, so a mismatch shows up as different header text after the first refresh

If the same report also uses calculated fields or calculated items, building and refreshing pivot tables with calculated fields in HotXLS covers how those interact with materialization, and XLSX pivot field schema validity in Delphi lists the field-level XML rules that keep Excel from offering to repair the file

Both property groups, dense ranking and refresh-stable extension markup are part of the HotXLS Delphi spreadsheet component, which reads and writes XLSX and XLS pivots from Delphi and C++Builder