Novis\Spreadsheet\Export::bytes
$export->bytes(): bytesReturns the whole spreadsheet as bytes, kept in memory.
Use it when the file goes somewhere other than a download or a path: into a database, an email attachment or a JSON response. The format is Excel (xlsx) unless the export was made with the option format: "csv". You can read the bytes back with Reader::open.
Good to know: the whole file is in memory until your program is done with it. For a large export, download and save send each part of the file as soon as it is ready. An export from fromRows with an array writes the same file each time you call it. A generator can be read only once, so a second call on that export throws a LogicError.
Return value
Returns bytes.
Examples
A csv export in memory
<?nvs// Shows how to get a CSV export as bytes in memory.use Novis\Spreadsheet\Workbook;
array<array<mixed>> $orders = [ ['order' => 1042, 'customer' => 'Ada', 'total' => 19.9], ['order' => 1043, 'customer' => 'Alan', 'total' => 5.0],];
// `bytes` returns the whole file. CSV is text, so `as string` prints it.bytes $file = Workbook::fromRows($orders, { format: 'csv' })->bytes();echo Core\Bytes::length($file), " bytes\n";echo $file as string;53 bytesorder,customer,total␍1042,Ada,19.9␍1043,Alan,5␍Read the export back
<?nvsuse Novis\Spreadsheet\Reader;// Shows how to make an Excel file in memory and read it back with `Reader`.use Novis\Spreadsheet\Workbook;
bytes $file = Workbook::fromRows([['item' => 'Pen', 'price' => 1.5], ['item' => 'Ink', 'price' => 4.25]])->bytes();
// `Reader::open` reads the bytes. The default sheet name is `Sheet1`.foreach (Reader::open($file)->rows('Sheet1', { header: true }) as var $row) { echo $row->values['item'], ' costs ', $row->values['price'], "\n";}Pen costs 1.5Ink costs 4.25A report inside a json response
<?nvs// Shows how to put a small CSV report inside a JSON response, as Base64 text.use Novis\Spreadsheet\Workbook;
bytes $file = Workbook::fromRows([['day' => 'Monday', 'visits' => 120], ['day' => 'Tuesday', 'visits' => 95]], { format: 'csv' })->bytes();
// JSON cannot contain bytes, so `Core\Encoding::toBase64` turns them into text.echo Core\Json::encode({ name: 'visits.csv', content: Core\Encoding::toBase64($file) }), "\n";
// The receiver turns the text back into the same file.echo Core\Encoding::fromBase64(Core\Encoding::toBase64($file)) as string;{"content":"77u/ZGF5LHZpc2l0cw0KTW9uZGF5LDEyMA0KVHVlc2RheSw5NQ0K","name":"visits.csv"}day,visits␍Monday,120␍Tuesday,95␍