Two rows of sales data: one sold a single unit for 10, the other sold nine units for 30. Drop a calculated field defined as =Revenue/Units onto the data area of a pivot and the total reads 4. Averaging the two per-row prices would give 6.67, adding them would give 13.33, and the pivot shows neither, because a calculated field is evaluated on the summed operands of each cell: 40 divided by 10
That rule is exactly right for an average ticket price and exactly wrong for anything computed row by row. Generated pivots have a few more places like it: the base field behind a "difference from previous" display, a cache that still describes last month's rows, and a grid nobody has filled in because the file has not been opened in Excel yet
Building an XLSX pivot table from Delphi with AddPivotTable
HotXLS creates a pivot with TXLSXWorksheet.AddPivotTable, which takes the source range in A1 notation, the 1-based row and column where the table anchors, and a name. The call reads the header row for field names (an empty header becomes Field1, Field2 and so on), scans every data row to collect each column's distinct values, infers a type per column, and returns a TXLSPivotTable whose fields all start off the axes. A second call against the same sheet and rectangle reuses the existing cache instead of building another one. On a bad range, an unknown sheet name or an anchor outside the sheet, the method returns nil
Fields go onto the layout with AddRowField, AddColumnField and AddPageField. AddDataFieldByName puts a column in the values area with one of eleven TXLSPivotAggregation functions: xlpaSum, xlpaCount, xlpaAverage, xlpaMax, xlpaMin, xlpaProduct, xlpaCountNums, xlpaStdDev, xlpaStdDevP, xlpaVar and xlpaVarP
uses
SysUtils, lxHandleX, lxPivot;
var
Book : TXLSXWorkbook;
Sheet: TXLSXWorksheet;
Pivot: TXLSPivotTable;
begin
Book := TXLSXWorkbook.Create;
try
Book.Open('sales.xlsx');
Sheet := Book.Sheets[1]; // report sheet; Sheets is 1-based
// Data!A1:E500 holds Region, Quarter, Year, Revenue, Units
Pivot := Sheet.AddPivotTable('Data!$A$1:$E$500', 3, 1, 'SalesByRegion');
if Pivot = nil then
raise Exception.Create('Pivot source range was rejected');
Pivot.AddRowField('Region');
Pivot.AddColumnField('Quarter');
Pivot.AddPageField('Year');
Pivot.AddDataFieldByName('Revenue', xlpaSum);
Pivot.AddDataFieldByName('Units', xlpaAverage);
Book.SaveAs('sales-pivot.xlsx');
finally
Book.Free;
end;
end;
A sheet name containing spaces goes in single quotes, as in 'Q3 Sales'!A1:E500, and a range without a prefix refers to the sheet you call the method on. The source for AddPivotTable is a rectangle; workbooks that address their data through a name follow the same A1 rules covered in defined names and cross-sheet references, and the refresh call further down resolves defined names and tables on its own
Why the cache and the table are two separate parts
An XLSX pivot is two parts that point at each other, and most of the surprises later in this article come from forgetting which part holds what. The pivotCacheDefinition is the data snapshot: a worksheetSource naming the source range, one cacheField per column with that column's distinct values in sharedItems, and a records part that stores each source row as indexes into those values. The pivotTableDefinition is the view: which field sits on which axis, the data fields and their functions, the layout switches. ECMA-376 Part 1 §18.10 defines both, and the view finds its cache through a cacheId registered in the workbook's pivotCaches list
One cache can back several views. The AddPivotTable overload that takes a TXLSPivotCache instead of a range string attaches a second view to an existing cache, so a "by region" and a "by quarter" table read the same snapshot and one refresh covers both. A freshly built cache also carries RefreshOnLoad = True, which writes refreshOnLoad="1" and asks Excel to rebuild the cache from the source the first time the file is opened. The classic .xls engine keeps the same split in a different wire format, described in the binary SX-record layout behind classic .xls pivots
What is the difference between a calculated field and a calculated item?
A calculated field is a new value column, and a calculated item is a new member inside an existing column; the three pivot terms that sound alike behave very differently. A calculated field such as average price derives a value from other columns and lives on the cache: you add a cache field, give it a formula through TXLSPivotCacheField.Formula, and mark it DatabaseField := False so the writer emits <cacheField formula="..." databaseField="0"> with no source column behind it. A calculated item lives inside one field and combines that field's members by name, so a Region field can grow a CoreMarkets row equal to North plus South; TXLSPivotField.AddCalculatedItem creates it. A calculated member, added with TXLSPivotTable.AddCalculatedMember, is a table-level definition whose MemberType is 'data' for a measure or empty for a dimension member, and it matters mostly for OLAP-shaped pivots
var
Cache : TXLSPivotCache;
PriceFld: TXLSPivotCacheField;
PriceVw : TXLSPivotField;
Region : TXLSPivotField;
begin
Cache := Pivot.Cache;
// Calculated FIELD: a cache column with a formula and no source data
PriceFld := Cache.AddField('AvgPrice', xlpcftNumber);
PriceFld.Formula := '=Revenue/Units';
PriceFld.DatabaseField := False;
// Expose it to this view; the second argument is its cache-field index
PriceVw := Pivot.AddField('AvgPrice', Cache.FieldCount - 1);
Pivot.AddDataField(PriceVw, xlpaSum).DisplayName := 'Average price';
// Calculated ITEM: a synthetic member of the Region field
Region := Pivot.FindFieldByName('Region');
Region.AddCalculatedItem('CoreMarkets', '=North+South');
Pivot.BindCalculatedItemsToCache; // before evaluating in process
end;
The calculated field goes into the values area with xlpaSum, and that is deliberate. Excel applies the formula to the summed operands of each cell, which is where the 4 in the opening example comes from, and the "Sum of" label is how Excel presents every calculated field. To put those numbers into the saved cells, materialize the table with TXLSXWorkbook.MaterializeNativePivotTable. That method evaluates calculated fields in Excel's order: it sums each referenced database field in the cell's context, leaf, subtotal or grand total, and then applies the formula. The opening example comes out as 40/10 = 4, and a grand total is its own ratio of sums, never the sum of the ratios shown above it. If you need a true per-row metric, compute it as an ordinary column in the source range before building the pivot
Calculated items have two sharp edges. The first is binding: an item added through AddCalculatedItem is a view-level definition until BindCalculatedItemsToCache appends its member and formula to the cache, and in-process evaluation needs that step. Because the binding lands on the cache, every view sharing it sees the new member. The second edge belongs to Excel. Excel refuses to add a calculated item to a field that has been grouped by number range or date, so keep calculated items on ungrouped fields and do the grouping elsewhere
How do you show pivot values as a percent of total?
Set TXLSPivotDataField.ShowDataAs and leave the numbers alone. The TXLSPivotShowDataAs enum mirrors the OOXML ST_ShowDataAs values: xlpsdaNormal, xlpsdaDifference, xlpsdaPercent, xlpsdaPercentDiff, xlpsdaRunTotal, xlpsdaPercentOfRow, xlpsdaPercentOfCol, xlpsdaPercentOfTotal and xlpsdaIndex. Placing the same source column in the values area twice, once raw and once as a share of the grand total, gives a report both the figure and its weight. Percent-of-parent and rank displays go through a separate ExtendedShowDataAs property
var
Share, Change: TXLSPivotDataField;
begin
Pivot.AddDataFieldByName('Revenue', xlpaSum).DisplayName := 'Revenue';
Share := Pivot.AddDataFieldByName('Revenue', xlpaSum);
Share.DisplayName := 'Share of total';
Share.ShowDataAs := xlpsdaPercentOfTotal; // no base needed
Change := Pivot.AddDataFieldByName('Revenue', xlpaSum);
Change.DisplayName := 'Change vs previous quarter';
Change.ShowDataAs := xlpsdaDifference;
Change.BaseField := 1; // Quarter, 0-based in this view
Change.BaseItem := xlPivotBaseItemPrevious; // or a 0-based item index
end;
xlpsdaDifference, xlpsdaPercent and xlpsdaPercentDiff need both BaseField and BaseItem; xlpsdaRunTotal needs only BaseField; the row, column, total and index modes need neither. BaseField is a 0-based position in the table's own field list. For a pivot built by AddPivotTable that list follows the source columns, so Quarter in column B is 1, and a calculated field you appended sits after the last source column. BaseItem is a 0-based item index in that field, or one of the two relative selectors, xlPivotBaseItemPrevious ($7FFB) and xlPivotBaseItemNext ($7FFC). Use the relative selectors for "change vs previous" reports: a fixed item index means "compare with Q1" and stays that way when the next quarter's data arrives
Grouping dates and numbers, and page-field filters
Grouping is set on the cache field because it changes how the source values are bucketed for every view of that cache. Get the field with Pivot.Cache.FindFieldByName, set HasGroup := True, then fill in either the numeric band (GroupStartNum, GroupEndNum, GroupInterval) or the date hierarchy (GroupByDate with GroupMonths, GroupQuarters, GroupYears and the other Group* flags, plus GroupStartDate and GroupEndDate). The writer emits the matching <fieldGroup><rangePr groupBy="months"/>, so an order-amount column grouped in 1000-wide bands opens already bucketed
Page fields are the filter drop-downs above the table. PageItemIndex pre-selects one cache item and defaults to xlPageItemAll ($7FFD, shown as "(All)"). MultipleItemSelectionAllowed := True lets the reader tick several items and is written as multipleItemSelectionAllowed="1" on the pivotField. Rules beyond a manual pick go in each field's Filters collection: Filters.Add returns a TXLSPivotFilter whose FilterType covers the count, percent, sum, caption, value, date and top/bottom families, with the operands in Value1 and Value2
How do you refresh a pivot cache when the source rows change?
TXLSXWorkbook.RefreshPivotCache re-reads the source and updates the cache in the same process, which is what a nightly job needs after it rewrites the data sheet. It returns 1 on success and -1 when the cache id is unknown or the source, its header row or its values cannot be refreshed. The source can be the original rectangle, a defined name or an Excel table, resolved to its current extent on every call. Existing members keep their indexes, new values are appended, and a region that vanished from the data stays in the cache's member list without producing a row, so page selections and base-item references set earlier still point at the same members
var
Data: TXLSXWorksheet;
begin
if not Book.Sheets.TryGetSheetByName('Data', Data) then
raise Exception.Create('Source sheet not found');
Data.Cells[2, 4].Value := 128000; // corrected Revenue in D2
Book.Recalculate; // refresh reads current cell values
if Book.RefreshPivotCache(Pivot.CacheId) <> 1 then
raise Exception.Create('Pivot cache refresh failed');
// Write the computed grid and Excel's layout XML; AvgPrice is
// evaluated on summed Revenue and Units, as Excel does on refresh
if Book.MaterializeNativePivotTable(Pivot) <> 1 then
raise Exception.Create('Pivot layout or output area is not supported');
Book.SaveAs('sales-pivot-refreshed.xlsx');
end;
The Recalculate call is there because refresh takes whatever value each cell holds right now; a Revenue column made of formulas still carries yesterday's results until the workbook is recalculated. Two failures deserve recognising before they show up in a log. Renaming, removing or adding a source column returns -1, because headers are matched to cache fields by name (case-insensitive); reordering columns is fine. A field with manual discrete groups also returns -1 when the new data contains a member no group maps. In both cases the previous cache stays intact, and the batch can report the file instead of shipping a half-updated pivot
A successful refresh also sets RefreshOnLoad to False, on the reasoning that the cache now matches the source. For a server job that delivers finished numbers, that default is the safer one. A workbook a person will edit and re-pivot in Excel can switch it back with Pivot.Cache.RefreshOnLoad := True, at the price of Excel rebuilding the cache on every open
Who computes the numbers in the pivot grid
A refreshed cache is still only data. The cells under the pivot hold whatever was last written there, and an application that reads cell values without refreshing pivots sees that, not the new totals. MaterializeNativePivotTable closes the gap: it evaluates the view from the current cache, writes the result grid at the table's FirstRow and FirstCol, and writes Excel's own compact-layout XML in the same transaction. It returns -1 when the layout falls outside the compact layouts it supports, or when the output would overwrite cells it does not own, such as data, a merged range or another pivot; the AAdoptExisting overload takes over plain values already sitting in the table's declared area on the first run. MaterializePivotTable writes the grid alone. A pivot that carries calculated fields goes through the native method, because there each calculated value is computed from summed operands, so the saved cells hold the same figures Excel shows after its own refresh
Leaving the grid to Excel is the other option. Skip materialization and keep refreshOnLoad="1", and Excel computes everything on open while every other reader of the file sees an empty or stale block. Materialize in process, and the saved cells carry the numbers, the downstream formulas that reference the pivot area can be recalculated, and Excel still treats the table as a live pivot it can refresh. For generated reports that leave the server, call MaterializeNativePivotTable after every refresh. Calculated field and item formulas still have to be valid Excel pivot formulas, since Excel evaluates them again on its next refresh. The rows that feed the pivot usually come from validated input sheets, and data validation, AutoFilter and structured tables covers that side of a report
Everything shown here, from AddPivotTable through cache refresh and grid materialization, ships in the HotXLS Delphi Excel Component for Delphi and C++Builder, which handles XLSX pivot parts and the classic BIFF8 pivot records through one object model