vensas / hypaxel
High-performance, constant-memory streaming XLSX (Excel) writer for PHP. Pure PHP, no extensions beyond zlib.
Requires
- php: >=8.2
- php-64bit: *
- ext-zlib: *
Requires (Dev)
- ext-zip: *
- friendsofphp/php-cs-fixer: ^3.75
- openspout/openspout: ^4.24 || ^5.0
- phpoffice/phpspreadsheet: ^4.0 || ^5.0
- phpstan/phpstan: ^2.1
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^11.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
High-performance, constant-memory XLSX (Excel) writer for PHP. Pure PHP, installed with Composer alone.
Hypaxel writes .xlsx files as a forward-only stream. Each row is serialized to XML the moment
you write it and compressed straight into a small buffer that is flushed to the destination, so
memory stays flat whether you export 10 rows or a million, and a download can start while your
query is still running.
- Fast: writes 100k rows × 10 columns in about 0.4 s, about 11x faster than OpenSpout and 40x faster than PhpSpreadsheet (see Performance).
- Constant memory: about 200 KiB of PHP heap per export, for 20,000 rows and for 400,000 alike.
- Streams anywhere: files,
php://output, sockets, PSR-7 streams, callbacks, generators. The destination does not have to be seekable; the ZIP container is written front to back, with automatic ZIP64. - Data you already have: arrays, generators, database cursors, associative arrays and objects.
- Real Excel types:
int,float,string,bool,DateTimeInterface,DateInterval, formulas, enums,Stringable.nullis an empty cell. - Styles and layout: fonts, fills, borders, alignment, number formats, column widths, row heights, merged cells, frozen panes, auto filters, hidden sheets, tab colors.
- Valid output: every feature is read back with PhpSpreadsheet and OpenSpout in the test suite.
- No extensions to build: needs PHP 8.2+ (64-bit) and the bundled
zlibextension. No runtime dependencies.
This is a native PHP port of the hypaxel Rust crate; the
.NET, Python and Node.js
versions use the same design.
Status: Milestone 1: creating Excel files.
Install
composer require vensas/hypaxel
Requires PHP 8.2 or later (64-bit) with ext-zlib.
Quick start
use Vensas\Hypaxel\ColumnSpec; use Vensas\Hypaxel\Xlsx; $orders = [ ['id' => 1, 'customer' => 'Ada', 'amount' => 1234.5, 'created' => new DateTimeImmutable()], ['id' => 2, 'customer' => 'Linus', 'amount' => 99.99, 'created' => new DateTimeImmutable()], ]; Xlsx::writeFile('orders.xlsx', $orders); $bytes = Xlsx::toString($orders, sheetName: 'Orders', columns: [ 'id', new ColumnSpec('customer', header: 'Customer', width: 30), new ColumnSpec('amount', numberFormat: '#,##0.00'), ]);
Records (associative arrays or objects) get a styled, frozen header row and an auto filter.
columns selects and orders the keys; without it the keys of the first record are used. Lists
are written as plain rows, and columns then supplies the header texts:
Xlsx::writeFile('matrix.xlsx', [[1, 'a'], [2, 'b']], columns: ['Id', 'Label']);
The data can be any iterable. Pass a generator or a database cursor and rows are fetched while
the file is being written:
$rows = $pdo->query('SELECT id, customer, amount FROM orders', PDO::FETCH_ASSOC); Xlsx::writeFile('orders.xlsx', $rows);
Streaming HTTP responses
Plain PHP
use Vensas\Hypaxel\Xlsx; Xlsx::download('orders.xlsx', $pdo->query('SELECT id, customer, amount FROM orders', PDO::FETCH_ASSOC));
download() sends Content-Type and Content-Disposition and streams the workbook to the
client.
Symfony
use Doctrine\DBAL\Connection; use Symfony\Component\HttpFoundation\StreamedResponse; use Vensas\Hypaxel\Xlsx; #[Route('/orders.xlsx')] public function export(Connection $db): StreamedResponse { $orders = $db->iterateAssociative('SELECT id, customer, amount FROM orders'); return new StreamedResponse(static fn () => Xlsx::output($orders), 200, Xlsx::headers('orders.xlsx')); }
Laravel
use Illuminate\Support\Facades\DB; use Vensas\Hypaxel\Xlsx; Route::get('/orders.xlsx', fn () => response()->streamDownload( static fn () => Xlsx::output(DB::table('orders')->select('id', 'customer', 'amount')->orderBy('id')->cursor()), 'orders.xlsx', ['Content-Type' => Xlsx::CONTENT_TYPE], ));
PSR-7 / PSR-15 (Slim, Mezzio, ...): write to the body stream through a callback. No PSR package is needed by Hypaxel itself.
use Vensas\Hypaxel\Writer; use Vensas\Hypaxel\Xlsx; $body = $response->getBody(); $writer = Writer::toCallback($body->write(...)); $writer->writeWorksheet('Orders', $orders); $writer->finish(); return $response->withHeader('Content-Type', Xlsx::CONTENT_TYPE);
Pull-based bodies (ReactPHP, Amp, Swoole, Symfony's iterable StreamedResponse):
Xlsx::stream($orders) is a generator that yields the file in chunks while it consumes its
source lazily.
| Helper | Destination |
|---|---|
Xlsx::writeFile($path, $data, ...) |
a file |
Xlsx::writeStream($resource, $data, ...) |
any writable stream resource |
Xlsx::toString($data, ...) |
a string (memory grows with the file) |
Xlsx::stream($data, ...) |
a generator of chunks |
Xlsx::output($data, ...) |
the response body, without headers |
Xlsx::download($filename, $data, ...) |
the response body, with headers |
Xlsx::headers($filename), Xlsx::contentDisposition($filename), Xlsx::CONTENT_TYPE |
header values for frameworks |
All of them take sheetName, columns, header, autoFilter and options as named arguments.
Streaming only reaches the client if nothing in between collects the response: turn off
zlib.output_compression and user-level output buffering for the request (.xlsx is already
compressed), and tell a buffering proxy such as nginx to pass the response through, for example
with the X-Accel-Buffering: no header.
Full control with Writer
use Vensas\Hypaxel\Formula; use Vensas\Hypaxel\HorizontalAlignment; use Vensas\Hypaxel\SheetOptions; use Vensas\Hypaxel\Style; use Vensas\Hypaxel\Styled; use Vensas\Hypaxel\Writer; $writer = Writer::toFile('report.xlsx'); $header = $writer->addStyle(Style::create()->bold()->fontColor('#FFFFFF')->fill('#305496')->align(HorizontalAlignment::Center)); $money = $writer->addStyle(Style::create()->numberFormat('#,##0.00')); $sheet = $writer->addWorksheet('Sales', new SheetOptions(freezeRows: 1, columnWidths: [20, 12, 14])); $sheet->writeRow(['Product', 'Date', 'Revenue'], $header); $sheet->writeRows([ ['Widget', new DateTimeImmutable('2024-05-01'), new Styled(1234.5, $money)], ['Gadget', new DateTimeImmutable('2024-05-02'), new Styled(99.99, $money)], ]); $sheet->writeRow(['Total', null, new Styled(new Formula('SUM(C2:C3)'), $money)]); $writer->finish();
Worksheets are written one at a time: adding a worksheet completes the previous one. Always call
finish(); it writes the parts that make the file a workbook.
Destinations
| Constructor | Destination |
|---|---|
Writer::toFile($path) |
creates or truncates a file; finish() closes it |
Writer::toStream($resource) |
any writable stream resource (php://output, php://memory, sockets, ...); stays open |
Writer::toCallback($callable) |
every chunk goes to callable(string): mixed |
Writer::toOutput() |
echo plus flush() per chunk |
Writer::inMemory() |
kept in memory; finish() returns the bytes, drain() takes what exists so far |
new Writer($sink) |
your own Vensas\Hypaxel\Sink\Sink (write(string), close()) |
Writer
| Method | Purpose |
|---|---|
addStyle(Style $style): StyleId |
Registers a format. Identical styles share a handle |
addWorksheet($name, ?SheetOptions $options): Worksheet |
Starts the next worksheet |
writeWorksheet($name, $data, columns:, header:, autoFilter:): int |
A worksheet from rows or records, with header row |
finish(): string |
Completes the workbook; returns the remaining bytes of an in-memory writer |
drain(): string, flush() |
Take the bytes of an in-memory writer / push buffered bytes to the destination |
currentWorksheet(), worksheetCount(), bytesWritten(), isFinished() |
State |
Worksheet
| Method | Purpose |
|---|---|
writeRow(iterable $values, ?StyleId $style) |
One row. $style applies to cells without their own |
writeRows(iterable $rows, ?StyleId $style): int |
Many rows from any iterable; returns the count |
writeRecords(iterable $records, array $columns): int |
One row per array or object, taking $columns in order |
write($value, ?StyleId $style), endRow() |
Cell-by-cell writing (chainable) |
beginRow(height:, style:, outlineLevel:, hidden:, collapsed:), beginRowAt($row, ...) |
Start a row with a height, row format or outline level, or further down |
skipCells($n), skipRows($n) |
Leave cells or rows empty |
mergeCells($r1, $c1, $r2, $c2), autoFilter($r1, $c1, $r2, $c2) |
Ranges, 1-based and inclusive |
addTable(Table $table) |
An Excel table over a range, see Excel tables |
row(), column() |
Current position |
Cell values
| PHP value | Excel cell |
|---|---|
string |
text (inline, or shared with sharedStrings) |
int, float |
number. NAN and INF become #NUM! |
bool |
boolean |
null |
empty; with a style, an empty cell carrying the format |
DateTimeInterface |
date serial, see Dates |
DateInterval |
duration in days, format [h]:mm:ss |
new Formula('SUM(A1:A9)') |
formula; a leading = is optional |
new Styled($value, $style) |
any of the above with its own format |
backed enum, unit enum, Stringable |
the enum's value, the case name, the string |
| arrays, other objects | UnsupportedValueException |
Styles
use Vensas\Hypaxel\{Alignment, Border, BorderLine, BorderStyle, Font, HorizontalAlignment, NumberFormat, Style, VerticalAlignment}; $fluent = Style::create() ->fontName('Arial')->fontSize(12)->bold()->italic()->underline()->strikethrough()->fontColor('#C00000') ->fill('#FFF2CC') ->border(BorderStyle::Thin, '#808080') ->align(HorizontalAlignment::Right)->valign(VerticalAlignment::Center)->wrap()->indent(1)->rotation(45) ->numberFormat('0.00%'); $explicit = new Style( numberFormat: NumberFormat::THOUSANDS2, font: new Font(name: 'Arial', size: 12, bold: true, color: '#C00000'), fill: '#FFF2CC', border: new Border(bottom: new BorderLine(BorderStyle::Double, '#000000')), alignment: new Alignment(wrapText: true), );
Styles are immutable value objects; every modifier returns a new instance. Colors are #RRGGBB
or #AARRGGBB strings or Color objects. BorderStyle has the 13 line styles of the format.
NumberFormat has constants for common format codes; any Excel format code works.
Worksheet options
new SheetOptions( freezeRows: 1, // rows pinned at the top freezeColumns: 0, // columns pinned at the left columnWidths: [20, null, 14], // from column A; null keeps the default columns: [5 => new Column(width: 30, style: $money, hidden: true)], // by 1-based column number showGridLines: true, hidden: false, tabColor: '#305496', rowOutlineLevels: 0, // deepest row outline level used, see Row groups outlineSummaryAbove: false, // group buttons on the summary row above the group autoFit: false, // true or new AutoFit(...), see Auto-fit columns );
Row groups
Rows started with beginRow() can carry an outline level (1-7), which Excel shows as
collapsible groups. Excel sizes the outline bar before it reads any row, so declare the deepest
level when adding the worksheet; a deeper row throws an InvalidArgumentException.
$sheet = $writer->addWorksheet('Regions', new SheetOptions(rowOutlineLevels: 2, outlineSummaryAbove: true)); $sheet->writeRow(['North', 300]); $sheet->beginRow(outlineLevel: 1)->writeRow(['Store A', 120]); $sheet->beginRow(outlineLevel: 2, hidden: true)->writeRow(['Till 1', 60]); $sheet->beginRow(outlineLevel: 1, collapsed: true)->writeRow(['Store B', 180]);
A row started with beginRow() that has no cells yet is filled by the next writeRow(),
writeRows() or writeRecords(); once it has cells, those start a new row as before.
hidden hides the row, collapsed marks the summary row of a collapsed group (hide the group's
rows as well).
Excel tables
use Vensas\Hypaxel\{Table, TableStyle}; $sheet->writeRow(['Product', 'Units']); $sheet->writeRows([['Widget', 3], ['Gadget', 5]]); $sheet->addTable(new Table(1, 1, $sheet->row(), 2, name: 'Orders', columns: ['Product', 'Units'], style: TableStyle::medium(9)));
A table gives a range a name for structured references (=SUM(Orders[Units])), filter buttons
and banded formatting. With a header row (the default), columns must repeat the header texts
exactly as written: Excel identifies table columns by them and repairs the file otherwise. Without
one (headerRow: false) the columns are named Column1, Column2, ... unless given.
| Parameter | Default | Meaning |
|---|---|---|
name |
Table1, Table2, ... |
Unique in the workbook (case-insensitive); letters, digits, _, ., no cell references such as A1 or R1C1 |
columns |
Column names: unique, 1-255 characters, one per column of the range | |
style |
TableStyle::default() (Medium 2) |
TableStyle::none(), light(1..21), medium(1..28), dark(1..11), or custom('Name') for a custom style defined in the workbook (1-255 characters, single line; written as given) |
headerRow, autoFilter, rowStripes |
true |
Header row, its filter buttons, banded rows |
columnStripes, highlightFirstColumn, highlightLastColumn |
false |
Banded columns, emphasized first/last column |
Tables may not overlap each other, merged cells or the worksheet's autoFilter() range: such
calls throw an OverlappingRangeException. Invalid names throw InvalidTableNameException,
taken ones DuplicateTableNameException. Definitions are kept in memory until the worksheet completes.
Auto-fit columns
$sheet = $writer->addWorksheet('Report', new SheetOptions(autoFit: true, columnWidths: [null, 12]));
Column widths come before the cells in the file, so with autoFit the worksheet's XML is held
back until the sample has been written: new AutoFit(sampleRows: 1000, maxWidth: 255.0) by
default, and at most 8 MiB of XML. The widths are then estimated from the sampled cells and
streaming continues; rows after the sample are not measured. Text (its longest line), numbers,
booleans and dates are measured with their number format, font size and boldness; formulas and
empty cells are not. Columns with an explicit width keep it. With autoFit off, nothing is held
back.
Options
$writer = Writer::toFile('report.xlsx', new Options(sharedStrings: true));
| Option | Default | Meaning |
|---|---|---|
compressionLevel |
1 |
Deflate level 0-9 |
sharedStrings |
false |
Shared string table: smaller files for repeated text, memory grows with the number of distinct strings |
flushThreshold |
65536 |
Compressed bytes buffered before a chunk goes to the destination (at least 1024) |
cellReferences |
false |
Write a reference such as B7 on every cell |
date1904 |
false |
Use the 1904 date system |
Dates
Excel has no time zones. A DateTimeInterface is written as the wall-clock time of the object's
own time zone: 2024-07-01 14:00 Europe/Berlin becomes 2024-07-01 14:00 in the sheet. Convert
with setTimezone() first if you want another zone.
Without a number format, a value at midnight gets Excel's locale-dependent short date format and
any other value the short date-and-time format. Give the cell or the column a format such as
NumberFormat::DATE to control it. Dates the date system cannot hold (before 1900, before 1904
with date1904, after 9999) are written as ISO 8601 text.
A DateInterval is written as a duration when it has a fixed length: one from diff(), or one
without years and months. Others throw an UnsupportedValueException, because a month has no
fixed number of days.
Notes and limits
- Write order: rows go top to bottom, cells left to right, one worksheet at a time. Column widths and frozen panes are set when the worksheet is added.
- Excel limits apply: 1,048,576 rows, 16,384 columns and 32,767 characters per cell. Exceeding
them throws a
LimitExceededException. A row rejected bywriteRow/writeRowsis not written at all, so the file stays valid if you catch the exception and continue. - Exceptions all extend
Vensas\Hypaxel\Exception\XlsxException:InvalidArgumentException,InvalidSheetNameException,DuplicateSheetNameException,InvalidTableNameException,DuplicateTableNameException,OverlappingRangeException,LimitExceededException,UnsupportedValueException,WriterStateException,IoException. - Text encoding: strings must be UTF-8. Invalid byte sequences are replaced with U+FFFD
instead of producing a file Excel refuses to open. Control characters and carriage returns are
written with Excel's
_xHHHH_escape and read back unchanged. - Numbers: every Excel number is a double, so integers beyond ±2^53 lose precision. Floats are written in their shortest form that reads back identically.
- Formulas are stored without cached results; Excel recalculates them when the file opens.
- Readers: by default, cell references that follow from a cell's position are omitted, which
the format allows and which makes files smaller and faster to write. References are written
for the rest of a row after an empty cell and for the rest of a worksheet after a skipped row,
which is what PhpSpreadsheet needs to place cells correctly. The test suite reads the default
output back with PhpSpreadsheet and OpenSpout. ExcelJS fails on omitted references (see the
Node.js notes); pass
cellReferences: truefor such readers. - Records: arrays,
ArrayAccessobjects and public properties are read by key. Use aColumnSpecwith avaluecallable for getters:new ColumnSpec('total', value: fn (Order $o) => $o->total()). - Styles belong to the writer that created them.
- Merged cells and tables are kept in memory until their worksheet completes.
Performance
Writing 10 columns per row (int, two strings, three floats, a DateTimeImmutable, a bool, a
second int and a string that is unique per row) from a generator to a file. Each case runs in its
own PHP process; "peak memory" is memory_get_peak_usage(true) of that process, which includes
the autoloader and the library's classes.
Measured on an Apple M1 Max (macOS 26.6) with PHP 8.4.8 (CLI, NTS) against OpenSpout 5.15.3 and PhpSpreadsheet 5.11.0.
opcache off (the CLI default)
| Case | 100k rows | Peak memory | 1M rows | Peak memory |
|---|---|---|---|---|
| Hypaxel, rows | 0.39 s | 4.0 MB | 3.85 s | 4.0 MB |
| Hypaxel, records with header | 0.53 s | 4.0 MB | 5.28 s | 4.0 MB |
| Hypaxel, rows, shared strings | 0.40 s | 13.5 MB | 4.01 s | 90.0 MB |
Hypaxel, rows, Xlsx::stream() |
0.43 s | 4.0 MB | 4.30 s | 4.0 MB |
| OpenSpout | 4.53 s | 4.0 MB | 44.46 s | 4.0 MB |
| PhpSpreadsheet | 16.38 s | 661.1 MB | not run | not run |
opcache with tracing JIT (opcache.enable_cli=1, opcache.jit=tracing, opcache.jit_buffer_size=128M)
| Case | 100k rows | Peak memory | 1M rows | Peak memory |
|---|---|---|---|---|
| Hypaxel, rows | 0.29 s | 4.0 MB | 2.87 s | 4.0 MB |
| Hypaxel, records with header | 0.37 s | 4.0 MB | 3.55 s | 4.0 MB |
| Hypaxel, rows, shared strings | 0.30 s | 13.5 MB | 2.99 s | 90.0 MB |
Hypaxel, rows, Xlsx::stream() |
0.31 s | 4.0 MB | 3.09 s | 4.0 MB |
| OpenSpout | 3.95 s | 4.0 MB | 38.77 s | 4.0 MB |
| PhpSpreadsheet | 10.98 s | 659.1 MB | not run | not run |
These are single runs on an otherwise idle machine, so treat small differences as noise. OpenSpout is a streaming writer too and uses as little memory as Hypaxel; the difference is time. PhpSpreadsheet builds the workbook in memory and is not run at 1M rows. The 1M-row file is 39 MB from Hypaxel and 52 MB from OpenSpout.
Run them yourself:
php benchmarks/bench.php # 100,000 rows php benchmarks/bench.php 1000000 php benchmarks/bench.php 100000 --jit # opcache + tracing JIT
What makes it fast in PHP
- One string per row, no objects per cell. Scalars are serialized inline in the row loop; there is no cell object and no method call per cell.
- One call per string. A single
preg_matchvalidates UTF-8 and detects everything that needs escaping orxml:space; clean text is copied as it is. - Compact XML. Cell references are only written where a reader needs them.
- Checksums from zlib. Entries are deflated with gzip framing, which is stripped again, so
zlib computes the CRC-32 while it compresses. On the test machine, compressing and
checksumming worksheet XML at level 1 ran at 434 MB/s this way and at 203 MB/s with a
separate
hash_update('crc32b')pass. - What remains: formatting floats. PHP has no cheaper way to get the shortest round-trip
form of a double than
json_encode, at about 0.2 to 0.3 µs per value; float-heavy sheets are bounded by it.
Development
cd php composer install composer test # PHPUnit; reads every file back with PhpSpreadsheet and OpenSpout composer analyse # PHPStan, level max with strict rules composer cs # PHP-CS-Fixer (PER-CS), dry run composer bench
Coverage needs the pcov or xdebug extension: composer test:coverage.
composer.lock is not committed, as usual for a library: CI resolves the newest dependencies
each PHP version allows.
The package is developed in the php/ directory of the
Hypaxel monorepo, which is the place for issues and pull
requests. The repository Packagist installs from is generated from that directory and is
read-only (how it is published).
License
Licensed under the Apache License, Version 2.0. Copyright 2026 vensas GmbH.