Files
PhpSpreadsheet/samples/PivotTable/pvt04_Read_PivotTable.php
T
oleibman 9565757138 Reorganize Samples and Improve Downloader Class
A follow-on activity to PR #5061. That PR added scrollbars to the dropdown lists when samples were run in a browser. Earlier changes had broken up a number of categories into multiple entries because the dropdown lists were too long and wound up truncated. With the scrollbars, it makes sense to re-consolidate many of those lists, such as ComplexNumbers, which are all essentially the same test as each other. Some break-ups are retained (e.g. Basic/1/2/3/4/5) because they differ substantially from sample to sample; that's kind of an arbitrary decision, but it will have to do for now. I also renamed some of the members so that like members sort together when listing the directory (e.g. all pivot table samples now start with `pvt`). The sample code is mostly unchanged; only the directory and/or member names are changed.

The download samples were moved to their own new directory, and now represent a complete set of all the write formats that we permit. Studying their code, an improvement for `Helper\Downloader` became evident. It had been used merely to copy an existing file to be downloaded. However, by changing the first parameter of `download` to be either the name of the file directory (the existing usage) *or* a `Writer` object poised to issue `save`, you can use it to download your spreadsheet without having to worry about the headers which the browser requires. It then becomes generally useful beyond being used in samples:
```php
$writer = new WriterType($spreadsheet);
$downloader = new Downloader($writer, 'suggestedFileName.xlsx');
$downloader->download();
```
2026-10-22 13:22:48 -07:00

91 lines
2.9 KiB
PHP

<?php
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as XlsxReader;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PivotTable\PivotField;
use PhpOffice\PhpSpreadsheet\Worksheet\PivotTable\PivotTableBuilder;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
require __DIR__ . '/../Header.php';
/** @var PhpOffice\PhpSpreadsheet\Helper\Sample $helper */
// First build a small workbook that contains a pivot table, so this sample is
// self-contained. (In practice you would just load an existing .xlsx file.)
$helper->log('Create a workbook containing a pivot table');
$spreadsheet = new Spreadsheet();
$dataSheet = $spreadsheet->getActiveSheet();
$dataSheet->setTitle('Data');
$dataSheet->fromArray(
[
['Region', 'Product', 'Amount'],
['East', 'Widget', 100],
['West', 'Widget', 150],
['East', 'Gadget', 200],
['West', 'Gadget', 250],
],
null,
'A1'
);
$pivotSheet = $spreadsheet->createSheet();
$pivotSheet->setTitle('PivotTable');
$builder = new PivotTableBuilder($dataSheet, 'A1:C5');
$builder
->addRowField('Region')
->addColumnField('Product')
->addDataField('Amount', PivotField::SUBTOTAL_SUM);
$builder->build($pivotSheet, 'A3', 'SalesByRegion');
$tempFile = $helper->getTemporaryFilename('xlsx');
(new XlsxWriter($spreadsheet))->save($tempFile);
$spreadsheet->disconnectWorksheets();
// Now read the file back and inspect its pivot tables.
$helper->log('Load the workbook and inspect its pivot tables');
$loaded = (new XlsxReader())->load($tempFile);
foreach ($loaded->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getPivotTableCollection() as $pivotTable) {
$helper->log(sprintf(
'Pivot table "%s" on sheet "%s" at %s',
$pivotTable->getName(),
$worksheet->getTitle(),
$pivotTable->getLocation()
));
$cache = $pivotTable->getCacheDefinition();
if ($cache !== null) {
$helper->log(sprintf(
' Source: %s!%s',
(string) $cache->getSourceWorksheet(),
(string) $cache->getSourceRange()
));
}
$helper->log(' Row fields: ' . implode(', ', names($pivotTable->getRowFields())));
$helper->log(' Column fields: ' . implode(', ', names($pivotTable->getColumnFields())));
$helper->log(' Page fields: ' . implode(', ', names($pivotTable->getPageFields())));
foreach ($pivotTable->getDataFields() as $dataField) {
$helper->log(sprintf(
' Value field: %s (%s)',
$dataField->getName(),
(string) $dataField->getSubtotal()
));
}
}
}
$loaded->disconnectWorksheets();
@unlink($tempFile);
/**
* @param PivotField[] $fields
*
* @return string[]
*/
function names(array $fields): array
{
return array_map(static fn (PivotField $field): string => $field->getName(), $fields);
}