OpenXLSX 1.12.1
Modern C++ Excel Library (Fork of OpenXLSX by Kenneth Troldal Balslev)
Loading...
Searching...
No Matches
Quick Start: Pivot Tables & Slicers

Introduction

OpenXLSX provides a powerful, enterprise-grade engine for generating dynamic Pivot Tables and interactive Slicers. The library natively performs O(1) memory deduplication and Cache Sharing, generating 100% OOXML-compliant tables that render perfectly across Microsoft Excel, Google Sheets, and WPS Office without relying on delayed calculations.

This tutorial covers:

  • Preparing the source data for a pivot table.
  • Utilizing the Fluent Builder API to define rows, columns, and aggregations.
  • Leveraging O(1) Pivot Cache Sharing for massive dashboards.
  • Reading, modifying, and deleting existing pivot tables (CRUD).
  • Adding interactive Slicers.

1. Preparing the Source Data

A pivot table requires a contiguous range of data with column headers in the first row. We start by creating a worksheet and filling it with our raw dataset.

#include <OpenXLSX.hpp>
using namespace OpenXLSX;
int main() {
doc.create("PivotDemo.xlsx", XLForceOverwrite);
// Create the raw data sheet
auto rawWks = doc.workbook().worksheet("Sheet1");
rawWks.setName("RawData");
// Add Headers
rawWks.cell("A1").value() = "Date";
rawWks.cell("B1").value() = "Region";
rawWks.cell("C1").value() = "SalesRep";
rawWks.cell("D1").value() = "Product";
rawWks.cell("E1").value() = "Revenue";
// Add some sample data rows...
rawWks.cell("A2").value() = "2026-Q1";
rawWks.cell("B2").value() = "North";
rawWks.cell("C2").value() = "Alice";
rawWks.cell("D2").value() = "Widget A";
rawWks.cell("E2").value() = 15000.0;
// ... [Assume more data is added up to row 13] ...
This class encapsulates the concept of an excel file. It is different from the XLWorkbook,...
Definition XLDocument.hpp:97
void create(std::string_view fileName, bool forceOverwrite=XLForceOverwrite)
Initialize a new .xlsx package from a built-in template.
Definition XLDocument.cpp:372
XLWorkbook workbook() const
Get the underlying workbook object, containing worksheets and global data state. [[nodiscard]] preven...
Definition XLDocument.cpp:828
void setName(const std::string &sheetName)
Method for renaming the sheet.
Definition XLSheetBase.hpp:212
XLWorksheet worksheet(std::string_view sheetName)
Get the worksheet with the given name.
Definition XLWorkbook.cpp:205
Definition IXLCellProvider.hpp:24
constexpr const bool XLForceOverwrite
Definition XLDocument.hpp:60

2. Creating a Pivot Table (Fluent API)

To create a pivot table, use the XLPivotTableOptions builder. The API is designed to be highly ergonomic, enforcing mandatory parameters (Name, Source, Target) in the constructor, and allowing you to chain configurations fluently.

doc.workbook().addWorksheet("Summary");
auto pivotWks = doc.workbook().worksheet("Summary");
// 1. Build the Pivot Table configuration fluently
auto options = XLPivotTableOptions("PivotSummary", "RawData!A1:E13", "B3")
.addFilterField("Region") // Page/Report Filter
.addRowField("SalesRep") // Row grouping
.addColumnField("Date") // Column grouping
.addDataField("Revenue", "Total Revenue", XLPivotSubtotal::Sum, 4) // Data aggregation (4 = '#,##0.00' format)
.setPivotTableStyle("PivotStyleMedium14") // Built-in Excel Theme
.setShowRowStripes(true) // Banded rows
.setRowGrandTotals(false); // Hide row grand totals
// 2. Apply and generate the Pivot Table
auto pt = pivotWks.addPivotTable(options);
// Optional: Tell Excel to refresh calculations on the next open
pt.setRefreshOnLoad(true);
Definition XLPivotTable.hpp:74
XLPivotTableOptions & setShowRowStripes(bool value)
Definition XLPivotTable.hpp:215
XLPivotTableOptions & setRowGrandTotals(bool value)
Definition XLPivotTable.hpp:165
XLPivotTableOptions & addFilterField(std::string fieldName, std::vector< std::string > selectedItems={})
Definition XLPivotTable.hpp:140
XLPivotTableOptions & addDataField(std::string fieldName, std::string customName="", XLPivotSubtotal subtotal=XLPivotSubtotal::Sum, uint32_t numFmtId=0, XLPivotShowValuesAsOptions showValuesAs={})
Definition XLPivotTable.hpp:118
XLPivotTableOptions & addRowField(std::string fieldName, std::vector< std::string > selectedItems={})
Definition XLPivotTable.hpp:88
XLPivotTableOptions & setPivotTableStyle(std::string styleName)
Definition XLPivotTable.hpp:155
XLPivotTableOptions & addColumnField(std::string fieldName, std::vector< std::string > selectedItems={})
Definition XLPivotTable.hpp:103
void addWorksheet(std::string_view sheetName)
Add a new worksheet.
Definition XLWorkbook.cpp:258
@ Sum
Definition XLPivotTable.hpp:23

3. O(1) Pivot Cache Sharing (Dashboards)

When building Dashboards with multiple Pivot Tables pulling from the exact same data source, OpenXLSX automatically detects the matching sourceRange and reuses the underlying pivotCacheDefinition.

This O(1) Cache Sharing prevents memory duplication and drastically reduces the final .xlsx file size.

// Create a second pivot table looking at the SAME source data
auto opts2 = XLPivotTableOptions("PivotByProduct", "RawData!A1:E13", "H3")
.addRowField("Product")
.addDataField("Revenue", "Product Revenue", XLPivotSubtotal::Sum);
// OpenXLSX natively reuses the cache from "PivotSummary" since the source matches!
pivotWks.addPivotTable(opts2);

4. Reading, Updating, and Deleting (CRUD)

OpenXLSX provides comprehensive CRUD operations to manage existing Pivot Tables, making it perfect for automated report generation where you need to keep a template's styles but swap out its data.

// 1. Read existing tables
auto allPivots = pivotWks.pivotTables();
for (auto& pivot : allPivots) {
std::cout << "Found Pivot: " << pivot.name() << " at " << pivot.targetCell() << std::endl;
}
// 2. Update (Change Data Source Range Dynamically)
// If you added 100 new rows to RawData, simply update the existing pivot table's bounds:
allPivots[0].changeSourceRange("RawData!A1:E113");
// 3. Delete
// Safely remove a pivot table and its associated XML relationships
pivotWks.deletePivotTable("PivotByProduct");

5. Adding Pivot Slicers

A Slicer is a visual filtering control that connects to a Pivot Table. Once the Pivot Table is created, use addPivotSlicer() to attach a slicer.

// Configure the slicer
sOpts.name = "Region"; // Must match the pivot field source column name
sOpts.caption = "Select Region"; // Display title shown on the slicer header
sOpts.style = XLSlicerStyle::Dark4;
sOpts.width = 160; // pixels
sOpts.height = 240; // pixels
// Anchor the slicer at cell "F5", connected to `pt`
pivotWks.addPivotSlicer("F5", pt, "Region", sOpts);
@ Dark4
Definition XLSlicer.hpp:34
Definition XLTables.hpp:35
uint32_t width
Definition XLTables.hpp:38
uint32_t height
Definition XLTables.hpp:39
std::string caption
Definition XLTables.hpp:37
std::string name
Definition XLTables.hpp:36

You can also access and modify the slicer after creation via the collection:

pivotWks.slicers()["Region"]
.setCaption("Filter: Region")
.showOnly({"North", "East"}); // Pre-select items programmatically
@ Light2
Definition XLSlicer.hpp:32

For Table Slicers (connected to XLTable instead of XLPivotTable), use wks.addTableSlicer().
See the full Slicer Tutorial for all options, multi-sheet usage, and OOXML compatibility notes.

6. Finalizing the Document

Save and close the document as usual.

doc.save();
doc.close();
return 0;
}
void close()
Close the document and release underlying ZIP resources, ensuring file handles are closed properly.
Definition XLDocument.cpp:412
void save()
Save changes to the original file path.
Definition XLDocument.cpp:460

When you open the generated PivotDemo.xlsx file, the native deduplication engine ensures your pivot tables and slicers are fully populated, styled, and interactive immediately!