---
title: "Writing XLSX — Imports for Laravel | Roundly"
description: "The public streaming XLSX writer (1.3.0) — Imports::xlsx(), XlsxWriter, SheetLayout and InputMessage, cell values, formula safety and limits."
url: https://roundly-consulting.com/open-source/docs/imports-for-laravel/writing-xlsx
language: en
---

[All packages](https://roundly-consulting.com/open-source.md)

[Imports for Laravel](https://roundly-consulting.com/open-source/docs/imports-for-laravel.md)

# Writing XLSX

The writer behind the package’s templates and error reports is public API since 1.3.0: RoundlyConsulting\\Imports\\Xlsx\\XlsxWriter, laid out with Xlsx\\SheetLayout and Xlsx\\InputMessage. It needs only ext-xmlwriter and ext-zip — no third-party spreadsheet library. Use it to export any data as .xlsx (reports, registers, lists), not only import-related files:

```php
use RoundlyConsulting\Imports\Facades\Imports;
use RoundlyConsulting\Imports\Xlsx\SheetLayout;

$writer = Imports::xlsx(storage_path('app/register.xlsx'));

$writer->addSheet('Register', (function () use ($activities) {
    yield ['Activity', 'Purpose', 'Legal basis', 'Reviewed on'];

    foreach ($activities->lazy() as $activity) {
        yield [$activity->name, $activity->purpose, $activity->legal_basis, $activity->reviewed_on];
    }
})(), new SheetLayout(
    boldHeader: true,
    freezeHeader: true,
    widths: [0 => 30, 1 => 50, 2 => 20, 3 => 14],
    formats: [3 => 'date'],
));

$writer->close();   // writes the file and removes the temp work directory
```

## Entry points

| Call | Work directory |
| --- | --- |
| `Imports::xlsx(string $path, bool $sharedStrings = false, bool $date1904 = false): XlsxWriter` | A fresh temp directory under imports.storage.tmp\_path, removed by close() — also when close() throws. A writer never closed leaves it to imports:sweep. |
| `XlsxWriter::temporary(string $path, bool $sharedStrings = false, bool $date1904 = false): XlsxWriter` | The same, without the facade. |
| `new XlsxWriter(string $path, string $workDirectory, bool $sharedStrings = false, bool $date1904 = false)` | Yours: give each writer its own directory. The sheet parts (sheet<N>.xml) stay in it after close(). |

Imports::xlsx() is a plain factory: Imports::fake() does not record it, and under the fake it still writes the file.

| Argument | Meaning |
| --- | --- |
| `$path` | Where close() writes the workbook. Its directory must exist; an existing file is overwritten. |
| `$sharedStrings` | Write strings to a shared-strings table instead of inline. Smaller files for repetitive text, but the table is held in memory until close() — leave it off for large or unique text. |
| `$date1904` | Use the 1904 date system (old Mac Excel). Leave it off. |

## XlsxWriter methods

| Method | Returns | Does |
| --- | --- | --- |
| `addSheet(string $name, iterable $rows, SheetLayout $layout = new SheetLayout)` | `void` | Streams one sheet. $rows is any iterable (array or generator) of list<string\|int\|float\|bool\|DateTimeInterface\|null>; column 0 is A. Sheets appear in the order added. |
| `defineName(string $name, string $range)` | `void` | A workbook defined name, e.g. defineName('Statuses', 'Lists!$A$1:$A$3') for a list validation. |
| `close()` | `void` | Zips the parts into $path. A workbook with no sheet gets an empty Sheet1. Throws RuntimeException when the file cannot be written. Call it once. |
| `static serial(DateTimeInterface $date, bool $date1904 = false)` | `float` | Excel’s serial day number for a date; the fraction is the time of day. |

## Cell values

| PHP value | Written as |
| --- | --- |
| `string` | Text — always, see Formula safety. XML-invalid control characters are stripped and invalid UTF-8 is scrubbed. More than 32,767 characters throws RuntimeException. |
| `int · float` | A number — floats with up to 15 decimal places, no exponent. |
| `bool` | A boolean (TRUE / FALSE). |
| `DateTimeInterface` | A date serial, formatted by the column’s format, else date when the time is midnight and datetime otherwise. The wall-clock date and time are written as they are — convert the timezone first. |
| `null · ''` | An empty cell. |

## Sheet names

Excel’s rules are applied for you: \[ \] : \* ? / \\ become \_, leading and trailing ' and spaces are trimmed, the name is cut to 31 characters (an empty name becomes Sheet) and a duplicate name (case-insensitive) gets \_2, \_3, ….

## SheetLayout

final readonly, every argument optional and named:

| Argument | Type | Effect |
| --- | --- | --- |
| `boldHeader` | `bool` | Row 1 in bold; its cells skip the column format. |
| `freezeHeader` | `bool` | Row 1 stays visible while scrolling. |
| `widths` | `array<int, float>` | Column index ⇒ width in Excel character units (default 12 for a column that has only a format). |
| `formats` | `array<int, string>` | Column index ⇒ 'text' (@), 'date' (yyyy-mm-dd), 'datetime' (yyyy-mm-dd hh:mm) or 'decimal:<scale>' (0.00 for scale 2; scale 0–10). Applies to the whole column, so cells a user types later get it too. |
| `lists` | `array<int, string>` | Column index ⇒ a dropdown: an inline list '"Yes,No"' (with the double quotes, ≤ 255 characters, no commas inside values) or a defined name. |
| `prompts` | `array<int, InputMessage>` | Column index ⇒ the message Excel shows when a cell is selected. |
| `validationRows` | `int` | How many rows below the header carry lists and prompts (rows 2 … validationRows + 1); 0 writes none. |
| `hidden` | `bool` | Hide the sheet, e.g. one holding dropdown values. |

InputMessage(string $title, string $prompt) is final readonly; the title is cut to 32 characters, the prompt to 255. Dropdowns, prompts, number formats and a hidden list sheet together:

```php
use RoundlyConsulting\Imports\Xlsx\{InputMessage, SheetLayout, XlsxWriter};

$writer = XlsxWriter::temporary(storage_path('app/tasks.xlsx'));

$writer->addSheet('Tasks', [
    ['Task', 'Status', 'Due', 'Budget'],
    ['Quarterly review', 'Open', new DateTimeImmutable('2026-12-15'), 1250.5],
], new SheetLayout(
    boldHeader: true,
    freezeHeader: true,
    formats: [2 => 'date', 3 => 'decimal:2'],
    lists: [1 => 'Statuses'],                       // a defined name, or an inline '"Open,Done"'
    prompts: [1 => new InputMessage('Status', 'Pick a status from the list.')],
    validationRows: 500,                             // rows 2 … 501 carry the dropdown and the prompt
));

// The dropdown values on a hidden sheet, named for the list validation
$writer->addSheet('Lists', [['Open'], ['In progress'], ['Done']], new SheetLayout(hidden: true));
$writer->defineName('Statuses', 'Lists!$A$1:$A$3');

$writer->close();
```

## Formula safety

Every string cell is written as text, never as a formula — inline (t="inlineStr") or, with $sharedStrings, as a shared string (t="s"). The writer never emits a cell formula (<f>). So user-entered values such as =1+1, +41 44 668 18 00, -2+3, @SUM(A1:A2) or =HYPERLINK(...) open in Excel and LibreOffice as the literal text and are never evaluated. The package’s tests pin this for both string modes, so the writer is safe for exporting user-entered text.

A string cell stays text until someone edits it in Excel and confirms it — Excel then parses what was typed, as it does for any cell. Two inputs are formula syntax by design and must come from your code, never from users: the SheetLayout lists values and the defineName() ranges.

## Limits

- No formulas, merged cells, sheet protection, colours, borders, images, hyperlinks or rich text. Styling is the bold header plus the column formats above.
- Rows stream to a file in the work directory as they come (flushed every 1,000 rows), so a generator of any length is never held in memory — 10,000 rows grow memory by well under 1 MB (pinned by a test). With $sharedStrings the distinct strings are held until close().
- Excel’s own limits apply: 1,048,576 rows and 16,384 columns per sheet, 32,767 characters per cell.
- It is the same writer whose templates and error reports users open in Excel and LibreOffice; the tests reopen every file they write with the package’s own reader (Imports::read()).

## Show your open-source love

This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.

[More ways to support, including crypto](https://roundly-consulting.com/support-us.md)

By donating, you agree to our [donation terms](https://roundly-consulting.com/donation-terms.md).

[Support our open source work (opens in a new tab)](https://donate.stripe.com/dRmeVe8FX5PF1Qd9pXcEw00) [Join us on Patreon (opens in a new tab)](https://www.patreon.com/cw/roundly)

## Want this built into your product?

We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.

[Get a quote in 48 hours](https://roundly-consulting.com/contact.md) [Browse all packages](https://roundly-consulting.com/open-source/docs/imports-for-laravel.md)
