PhpSpreadsheet/samples/DefinedNames/SimpleNamedFormula.php
oleibman 6fe653179f
Make DefinedNames Samples Consistent With Other Samples (#1707)
All other Samples write to temporary directory. DefinedNames samples
write to main directory, which (a) means they aren't stored with others,
and (b) they aren't ignored by git so look like changed files.
The tests are also simplified by requiring Header rather than Bootstrap,
making use of Helper.
2020-11-11 11:02:04 +01:00

44 lines
1.5 KiB
PHP

<?php
use PhpOffice\PhpSpreadsheet\NamedFormula;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
require_once __DIR__ . '/../Header.php';
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->setActiveSheetIndex(0);
// Add some Named Formulae
// The first to store our tax rate
$spreadsheet->addNamedFormula(new NamedFormula('TAX_RATE', $worksheet, '=19%'));
// The second to calculate the Tax on a Price value (Note that `PRICE` is defined later as a Named Range)
$spreadsheet->addNamedFormula(new NamedFormula('TAX', $worksheet, '=PRICE*TAX_RATE'));
// Set up some basic data
$worksheet
->setCellValue('A1', 'Tax Rate:')
->setCellValue('B1', '=TAX_RATE')
->setCellValue('A3', 'Net Price:')
->setCellValue('B3', 19.99)
->setCellValue('A4', 'Tax:')
->setCellValue('A5', 'Price including Tax:');
// Define a named range that we can use in our formulae
$spreadsheet->addNamedRange(new NamedRange('PRICE', $worksheet, '=$B$3'));
// Reference the defined formulae in worksheet formulae
$worksheet
->setCellValue('B4', '=TAX')
->setCellValue('B5', '=PRICE+TAX');
$helper->log(sprintf(
'With a Tax Rate of %.2f and a net price of %.2f, Tax is %.2f and the gross price is %.2f',
$worksheet->getCell('B1')->getCalculatedValue(),
$worksheet->getCell('B3')->getValue(),
$worksheet->getCell('B4')->getCalculatedValue(),
$worksheet->getCell('B5')->getCalculatedValue()
));
$helper->write($spreadsheet, __FILE__, ['Xlsx']);