MNB PHPExcelDeveloper Guide
v2.0.5

Pivot examples

Pivot Excel examples, explained clearly.

Open a focused example to see the implementation path, copy-ready PHP, expected workbook behavior, and the production boundary that matters.

2examples in this category
21focused categories
5implementation paths
01
Create Pivot Table

Generate a native pivot table from a source worksheet and define row fields and value aggregations.

MediumDirect API
addPivotTable()
create-pivot-table.php
<?php

use Mnb\PHPExcel\MnbExcel;

MnbExcel::fromWorkbookArray([
    'Data' => $salesRows,
    'Pivot' => [],
])
    ->withHeader()
    ->addPivotTable(
        name: 'SalesByRegion',
        sourceSheet: 'Data',
        sourceRange: 'A1:D500',
        targetCell: 'A1',
        options: [
            'sheet' => 'Pivot',
            'rows' => ['Region'],
            'values' => [[
                'field' => 'Amount',
                'function' => 'sum',
                'name' => 'Total Sales',
            ]],
            'layout' => 'tabular',
        ]
    )
    ->save('sales-pivot.xlsx');
02
Pivot Charts

Create a pivot summary and then add a chart that points to the pivot output range.

MediumDirect API
addPivotTable()addChart()
pivot-charts.php
<?php

use Mnb\PHPExcel\MnbExcel;

MnbExcel::fromWorkbookArray([
    'Data' => $salesRows,
    'Pivot' => [],
])
    ->withHeader()
    ->addPivotTable('SalesPivot', 'Data', 'A1:D500', 'A1', [
        'sheet' => 'Pivot',
        'rows' => ['Region'],
        'values' => [['field' => 'Amount', 'function' => 'sum']],
    ])
    ->addChart('column', 'Sales by Region', [[
        'name' => 'Sales',
        'categories' => 'Pivot!$A$2:$A$8',
        'values' => 'Pivot!$B$2:$B$8',
    ]], [
        'sheet' => 'Pivot',
        'from' => 'D2',
        'to' => 'L18',
    ])
    ->save('pivot-chart.xlsx');