Skip to content

Novis\Spreadsheet\Workbook::createForFile

Starts a spreadsheet that your program writes to a file at a path.

A path that ends in .csv makes a CSV file, .ods makes an OpenDocument file (ods), and any other path makes an Excel file (xlsx). The workbook writes to a temporary file in the same folder. finish gives it the name $path and returns a Written with the row count of each sheet and the file size. Its bytes is null.

Good to know: if a write fails, the temporary file is deleted and the file at $path does not change. On a server, a program needs the fs.write capability in nvs.toml for the folder of the path. A program you start from the command line may write any path.

A CSV file is UTF-8 with , between values. It starts with a byte order mark and ends each line with CR and LF, so Excel opens it correctly. csv sets its separator, quote and charset.

The examples below save an Excel file and read it back, save a CSV file, save two sheets with the summary first, save a CSV file with ; in Windows-1252, and save an ods file.

Parameters

  • $pathstring
  • $optionsOptionsdefault null

Return value

Returns Workbook.

Examples

Save a monthly report

<?nvs
use Novis\Spreadsheet\Reader;
// Shows how to write an Excel file to a path and read it back.
use Novis\Spreadsheet\Workbook;
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'sales-2024-05.xlsx');
// The file at `$path` is created, or replaced if it exists.
var $book = Workbook::createForFile($path);
$book->addSheet('Sales')->addRows([
['day' => Core\Time\Date::at(2024, 5, 1), 'sales' => 1200],
['day' => Core\Time\Date::at(2024, 5, 2), 'sales' => 950],
]);
// For a file, `Written::bytes` is `null`. The file is on the disk.
var $written = $book->finish();
echo $written->rows['Sales'], ' rows, bytes in memory: ', $written->bytes == null ? 'none' : 'yes', "\n";
// `header: true` uses the first row as the keys of each row. A date cell is read as a date.
foreach (Reader::open(Core\IO::open($path, Core\IO::FileMode::Read))->rows('Sales', { header: true }) as var $row) {
mixed $day = $row->values['day'];
if ($day is Core\Time\Date) {
echo $day->format('yyyy-MM-dd'), ': ', $row->values['sales'], "\n";
}
}
Output
2 rows, bytes in memory: none
2024-05-01: 1200
2024-05-02: 950

The same export as a csv file

<?nvs
// Shows that a path that ends in `.csv` makes a CSV file.
use Novis\Spreadsheet\Workbook;
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'orders.csv');
var $book = Workbook::createForFile($path);
$book->addSheet('Orders')->addRows([
['order' => 1042, 'customer' => 'Ada', 'total' => 19.9],
['order' => 1043, 'customer' => 'Alan', 'total' => 5.0],
]);
$book->finish();
// This prints the text of the file.
echo Core\IO::readText($path);
Output
order,customer,total␍
1042,Ada,19.9␍
1043,Alan,5␍

A nightly export with a summary first

<?nvs
use Novis\Spreadsheet\Reader;
// Shows a nightly job that saves an export of two sheets, with the summary as the first tab.
use Novis\Spreadsheet\Workbook;
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'nightly.xlsx');
var $book = Workbook::createForFile($path, { properties: { title: 'Nightly orders', company: 'Shop' } });
// The rows of a sheet are written first, and its totals are known at the end.
array<array<mixed>> $orders = [['order' => 1042, 'total' => 19.9], ['order' => 1043, 'total' => 5.0]];
$book->addSheet('Orders')->addRows($orders);
// `position: 0` puts this sheet first in the file, but it is written second.
$book->addSheet('Summary', { position: 0 })->addRow(['orders' => 2, 'total' => 24.9]);
$book->finish();
// This prints the sheets in the order a person sees their tabs.
foreach (Reader::open(Core\IO::open($path, Core\IO::FileMode::Read))->sheets() as var $sheet) {
echo $sheet->position, ' ', $sheet->name, "\n";
}
Output
0 Summary
1 Orders

A csv file for excel in europe

<?nvs
// Shows how to save a CSV file with `;` between values, in the Windows-1252 charset.
use Novis\Spreadsheet\Reader;
use Novis\Spreadsheet\Workbook;
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'prices.csv');
// `csv` sets the separator and the charset that the file is written in.
var $book = Workbook::createForFile($path, { csv: { separator: ';', charset: Core\Charset::Windows1252 } });
$book->addSheet('Prices')->addRows([
['Item' => 'Müsli', 'Price' => '3,50 €'],
['Item' => 'Käse', 'Price' => '4,20 €'],
]);
echo $book->finish()->size, " bytes\n";
// Each of `ü`, `ä` and `€` is one byte in Windows-1252. Read the file back with the same options.
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);
foreach (Reader::open($file, { csv: { separator: ';', charset: Core\Charset::Windows1252 } })->rows(0, { header: true }) as var $row) {
echo $row->values['Item'], ' costs ', $row->values['Price'], "\n";
}
$file->close();
Output
39 bytes
Müsli costs 3,50 €
Käse costs 4,20 €

An ods file for libreoffice

<?nvs
// Shows how to save an OpenDocument file (ods), which LibreOffice opens.
use Novis\Spreadsheet\Formula;
use Novis\Spreadsheet\Reader;
use Novis\Spreadsheet\Workbook;
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'stock.ods');
// A path that ends in `.ods` makes an ods file. The calls are the same as for an xlsx file.
var $book = Workbook::createForFile($path);
$book->addSheet('Stock')->addRows([
['Item' => 'Widget', 'Count' => 12],
['Item' => 'Gadget', 'Count' => 5],
['Item' => 'Total', 'Count' => Formula::of('SUM(B2:B3)', { cached: 17 })],
]);
echo $book->finish()->rows['Stock'], " rows\n";
// The reader reads the file back. The total is the cached value of the formula.
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);
foreach (Reader::open($file)->rows(0, { header: true }) as var $row) {
echo $row->values['Item'], ': ', $row->values['Count'], "\n";
}
$file->close();
Output
3 rows
Widget: 12
Gadget: 5
Total: 17