Skip to content

Novis\Spreadsheet\Export::to

$export->to(Core\IO\File $file): Written$export->to(
    Core\IO\File $file,
): Written

Writes the spreadsheet to a file that your program already opened for writing.

to writes the file from the current position of $file, and returns a Written with the number of rows of each sheet and the size in bytes. It does not close $file, so your program can write more to it and then close it.

Good to know: an open file has no name to read the format from. The format is Excel (xlsx) unless the export was made with the option format: "csv".

Parameters

  • $fileCore\IO\File

Return value

Returns Written.

Examples

Write orders to an open file

<?nvs
// Shows how to write an orders export to a file that your program opened.
use Novis\Spreadsheet\Workbook;
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'orders.csv');
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Write);
// An open file has no name to read the format from, so `format: "csv"` sets it.
Workbook::fromRows([['order' => 1042, 'total' => 19.9], ['order' => 1043, 'total' => 5.0]], { format: 'csv' })->to($file);
// `to` does not close the file. Your program closes it.
$file->close();
echo Core\IO::readText($path);
Output
order,total␍
1042,19.9␍
1043,5␍

A title line before the rows

<?nvs
// Shows how to write your own line to a file first, and the rows after it.
use Novis\Spreadsheet\Workbook;
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'stock.csv');
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Write);
$file->write("# Stock count, warehouse 2\n");
// `to` writes from where the file is now, so the rows come after the first line.
var $written = Workbook::fromRows([['item' => 'Pen', 'count' => 120], ['item' => 'Pad', 'count' => 45]], { format: 'csv' })->to($file);
$file->close();
echo Core\IO::readText($path);
echo $written->rows['Sheet1'], " rows\n";
Output
# Stock count, warehouse 2
item,count␍
Pen,120␍
Pad,45␍
2 rows

An excel file to an open file

<?nvs
use Novis\Spreadsheet\Reader;
// Shows how to write an Excel file to an open file and read it back.
use Novis\Spreadsheet\Workbook;
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'prices.xlsx');
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Write);
// With no `format` option, the file is an Excel file.
Workbook::fromRows([['item' => 'Pen', 'price' => 1.5], ['item' => 'Ink', 'price' => 4.25]], { sheet: 'Prices' })->to($file);
$file->close();
foreach (Reader::open(Core\IO::open($path, Core\IO::FileMode::Read))->rows('Prices', { header: true }) as var $row) {
echo $row->values['item'], ' costs ', $row->values['price'], "\n";
}
Output
Pen costs 1.5
Ink costs 4.25