Novis\Spreadsheet\Template::fill
Fills the placeholders of a template with your data and returns an Export.
A placeholder is text such as {{month}} or {{customer.name}} in a cell of the template. Each dot is one level of the array you pass. A cell that has only a placeholder gets the type of the value, and keeps its style. A row with a list placeholder, such as {{items.qty}}, is written once for each item of the list items. A list is an array or an Iterator. Every row below it moves down, with its notes, links and page breaks. A formula such as SUM(D3:D3) grows to cover all the items.
Good to know: a missing placeholder throws a LogicError that names the cell. The error can come from fill or from the call that writes the file, so put both in the try block. The filled file has no macros, ActiveX controls, custom ribbons or OLE objects. Excel computes every formula again when it opens the file.
The examples below fill a report with a list of items, fill values from nested arrays, show the errors, and fill a list on each of two sheets.
Parameters
$dataarray<mixed>
Return value
Returns Export.
Examples
A monthly report with an item list
<?nvs// Shows how to fill a monthly sales report from a template with a list of items.use Novis\Spreadsheet\Formula;use Novis\Spreadsheet\Reader;use Novis\Spreadsheet\Template;use Novis\Spreadsheet\Workbook;
// This workbook is the template. In a real program it is a file made in Excel.// Row 3 is the item row, and row 4 adds up the totals.var $design = Workbook::createInMemory();$design->addSheet('Report')->addRows([ ['Sales for {{month}}', '{{shop}}'], ['Product', 'Sold', 'Price', 'Total'], ['{{items.product}}', '{{items.sold}}', '{{items.price}}', Formula::of('B3*C3')], ['Sum', null, null, Formula::of('SUM(D3:D3)')],]);bytes $template = $design->finish()->bytes ?? Core\Bytes::fill(0, 0);
// `fill` writes row 3 once for each item. The sum row moves down and covers every item.bytes $report = Template::open($template)->fill([ 'month' => 'May 2024', 'shop' => 'Shop', 'items' => [ ['product' => 'Pen', 'sold' => 120, 'price' => 1.5], ['product' => 'Ink', 'sold' => 40, 'price' => 4.25], ['product' => 'Pad', 'sold' => 75, 'price' => 2.75], ],])->bytes();
// `formulas: true` reads a formula cell as a `Formula`, so this prints its text.foreach (Reader::open($report)->rows('Report', { formulas: true }) as var $row) { echo 'row ', $row->number; foreach ($row->values as tainted string $column => mixed $value) { echo ' ', $column, ': ', $value is Formula ? '=' . $value->text : Core\Json::encode($value); } echo "\n";}row 1 A: "Sales for May 2024" B: "Shop"row 2 A: "Product" B: "Sold" C: "Price" D: "Total"row 3 A: "Pen" B: 120 C: 1.5 D: =B3*C3row 4 A: "Ink" B: 40 C: 4.25 D: =B4*C4row 5 A: "Pad" B: 75 C: 2.75 D: =B5*C5row 6 A: "Sum" D: =SUM(D3:D5)Nested keys and dates
<?nvs// Shows how a placeholder such as `{{customer.name}}` finds a value inside nested arrays.use Novis\Spreadsheet\Cell;use Novis\Spreadsheet\Reader;use Novis\Spreadsheet\Style;use Novis\Spreadsheet\Template;use Novis\Spreadsheet\Workbook;
// The date cell of the template has a date format. `fill` keeps the format of each cell.var $design = Workbook::createInMemory();$design->addSheet('Invoice')->addRows([ ['Customer', '{{customer.name}}'], ['City', '{{customer.address.city}}'], ['Date', Cell::of('{{date}}', Style::of({ format: 'yyyy-mm-dd' }))], ['Paid', '{{paid}}'],]);bytes $template = $design->finish()->bytes ?? Core\Bytes::fill(0, 0);
// Each dot in a placeholder is one level of the array.// A date from `Core\Time` is written as a date, and `true` is written as a boolean.bytes $invoice = Template::open($template)->fill([ 'customer' => ['name' => 'Shop', 'address' => ['city' => 'Berlin']], 'date' => Core\Time\Date::at(2024, 5, 31), 'paid' => true,])->bytes();
foreach (Reader::open($invoice)->rows('Invoice') as var $row) { mixed $value = $row->values['B']; if ($value is Core\Time\Date) { echo $row->values['A'], ': the date ', $value->format('yyyy-MM-dd'), "\n"; } else { echo $row->values['A'], ': ', Core\Json::encode($value), "\n"; }}Customer: "Shop"City: "Berlin"Date: the date 2024-05-31Paid: trueA missing value throws an error
<?nvs// Shows the error you get when the data has no value for a placeholder.use Novis\Spreadsheet\Template;use Novis\Spreadsheet\Workbook;
var $design = Workbook::createInMemory();$design->addSheet('Invoice')->addRows([ ['Invoice {{number}}', '{{customer.name}}'],]);bytes $template = $design->finish()->bytes ?? Core\Bytes::fill(0, 0);
// The data has `customer`, but not `customer.name`. The error names the cell and the placeholder.// Put the call that writes the file, here `bytes`, inside the `try` block too.try { Template::open($template)->fill(['number' => 42, 'customer' => ['email' => 'shop@example.com']])->bytes();} catch (LogicError $e) { echo $e->message, "\n";}
// A value of `null` is allowed. The cell is empty.bytes $file = Template::open($template)->fill(['number' => 42, 'customer' => ['name' => null]])->bytes();echo Core\Bytes::length($file) > 0 ? 'the file is written' : 'the file is empty', "\n";
// `fill` can be called once on each template. Open the template again for a second file.var $once = Template::open($template);$once->fill(['number' => 1, 'customer' => ['name' => 'Shop']]);try { $once->fill(['number' => 2, 'customer' => ['name' => 'Blog']]);} catch (LogicError $e) { echo $e->message, "\n";}The template's cell `Invoice!B1` has the placeholder `{{customer.name}}`, which the data does not have.the file is writtenThe template is already filled. Call `fill` once.Lists on two sheets
<?nvs// Shows how to fill a list on each of two sheets, with one list from a generator.use Novis\Spreadsheet\Formula;use Novis\Spreadsheet\Reader;use Novis\Spreadsheet\Template;use Novis\Spreadsheet\Workbook;
final class Orders{ // This generator gives one order at a time. A real program can read them from a database. public static function all(): Iterator<array<mixed>> { yield ['number' => 101, 'total' => 30]; yield ['number' => 102, 'total' => 45]; yield ['number' => 103, 'total' => 25]; }}
// Each sheet has one list row. The total on `Summary` uses the sum on `Orders`.var $design = Workbook::createInMemory();$design->addSheet('Orders')->addRows([ ['Order', 'Total'], ['{{orders.number}}', '{{orders.total}}'], ['Sum', Formula::of('SUM(B2:B2)')],]);$design->addSheet('Summary')->addRows([ ['Cost', 'Amount'], ['{{costs.name}}', '{{costs.amount}}'], ['Profit', Formula::of('Orders!B3-SUM(B2:B2)')],]);bytes $template = $design->finish()->bytes ?? Core\Bytes::fill(0, 0);
// The sum on `Orders` moves to row 5. The formula on `Summary` changes to `Orders!B5`.bytes $report = Template::open($template)->fill([ 'orders' => Orders::all(), 'costs' => [ ['name' => 'Rent', 'amount' => 50], ['name' => 'Power', 'amount' => 10], ],])->bytes();
var $reader = Reader::open($report);array<string> $sheets = ['Orders', 'Summary'];foreach ($sheets as string $sheet) { echo $sheet, "\n"; foreach ($reader->rows($sheet, { formulas: true }) as var $row) { echo 'row ', $row->number; foreach ($row->values as tainted string $column => mixed $value) { echo ' ', $column, ': ', $value is Formula ? '=' . $value->text : Core\Json::encode($value); } echo "\n"; }}Ordersrow 1 A: "Order" B: "Total"row 2 A: 101 B: 30row 3 A: 102 B: 45row 4 A: 103 B: 25row 5 A: "Sum" B: =SUM(B2:B4)Summaryrow 1 A: "Cost" B: "Amount"row 2 A: "Rent" B: 50row 3 A: "Power" B: 10row 4 A: "Profit" B: =Orders!B5-SUM(B2:B3)