Skip to content
Docs: Hypaxel for .NETMenu

Hypaxel for .NET

Memory-efficient Excel in .NET: stream XLSX exports from ASP.NET Core and EF Core with no allocations in the write loop, and read large XLSX files row by row.

v0.3.0 unreleasedLast updated View as Markdown

Exporting large Excel files from a .NET service usually means building the whole workbook in memory first, which costs time, gigabytes of allocations and a long wait before the download starts. Hypaxel for .NET writes .xlsx files as a forward-only stream instead: each cell is serialized to UTF-8 XML the moment you write it and compressed straight into the output. Memory stays flat whether you export 100 rows or 10 million, the write loop allocates nothing with default settings, and the first bytes reach the HTTP client while your EF Core query is still running.

The same package also reads .xlsx files as a stream with XlsxReader. Rows are decompressed and parsed one at a time, so memory is bounded by the workbook’s shared strings plus one row, and numbers, booleans and dates are read without allocating. Editing existing workbooks is planned for a later milestone.

Compatibilityv0.3.0 unreleased
Package
Hypaxel, Hypaxel.AspNetCore
Requires
.NET 8, 9, 10, 11
Engine
Native .NET, no dependencies; writer and streaming reader
Web
ASP.NET Core: Results.Extensions.Excel(...), this.Excel(...)
Registry
NuGet (not published yet)
License
Apache-2.0

Install#

Install · NuGet
dotnet add package Hypaxel
dotnet add package Hypaxel.AspNetCore

Not published yetHypaxel, Hypaxel.AspNetCore are not on NuGet yet. The command above is what installation will look like once it is.

The package is not published yet. Until then, build it from source: see Building from source.

PackagePurpose
HypaxelCore writer and streaming reader (net8.0, net9.0, net10.0, net11.0), no dependencies
Hypaxel.AspNetCoreIResult / IActionResult helpers for streaming workbooks as HTTP responses

Quick start#

using Hypaxel;
using Hypaxel.Styling;

await using var writer = XlsxWriter.Create("report.xlsx");

var header = writer.AddStyle(new CellStyle
{
    Font = new Font { Bold = true, Color = ExcelColor.White },
    Fill = new Fill(ExcelColor.FromHex("#305496")),
});
var money = writer.AddStyle(new CellStyle { NumberFormat = NumberFormats.Thousands2 });

var sheet = writer.AddWorksheet("Sales", new WorksheetOptions { FrozenRows = 1 }.SetColumnWidths(20, 12, 14));

await sheet.AddRowAsync(CellValue.From("Product", header), CellValue.From("Date", header), CellValue.From("Revenue", header));
await sheet.AddRowAsync("Widget", new DateOnly(2024, 5, 1), CellValue.From(1234.5, money));
await sheet.AddRowAsync("Gadget", new DateOnly(2024, 5, 2), CellValue.From(99.99, money));
await sheet.AddRowAsync("Total", CellValue.Empty, CellValue.Formula("SUM(C2:C3)", money));

await writer.CompleteAsync();

Cell-by-cell writing for hot loops#

For the hottest loops, write cells one at a time. No CellValue is created:

foreach (var order in orders)
{
    sheet.Write(order.Id);
    sheet.Write(order.Customer);
    sheet.Write(order.Total, money);
    sheet.Write(order.CreatedAt);      // DateTime → Excel date, formatted automatically
    await sheet.EndRowAsync();         // flushes to the destination when the buffer is full
}

ASP.NET Core#

Hypaxel.AspNetCore streams a workbook as the response body. It never performs synchronous I/O, so it is safe on Kestrel’s response body with AllowSynchronousIO = false and works with non-seekable streams. It accepts IAsyncEnumerable<T>, so EF Core results stream from the database to the browser.

using Hypaxel.AspNetCore;

// One line: objects → worksheet with header, frozen top row and auto filter.
app.MapGet("/orders.xlsx", (AppDb db) =>
    Results.Extensions.Excel(db.Orders.AsNoTracking().AsAsyncEnumerable(), "orders"));

// Full control.
app.MapGet("/report.xlsx", () => Results.Extensions.Excel(async (writer, ct) =>
{
    var sheet = writer.AddWorksheet("Summary");
    await sheet.AddRowAsync(["Generated", DateTime.UtcNow], ct);
    await writer.WriteWorksheetAsync("Orders", LoadOrders(), ct);
}, fileName: "report"));

// MVC
public IActionResult Export() => this.Excel(_service.GetRows(), "export");

ExcelResult sets the content type and Content-Disposition headers, turns off response buffering, and passes HttpContext.RequestAborted through so a cancelled download stops the export.

Object mapping#

Export any IEnumerable<T> or IAsyncEnumerable<T> with a header row, frozen pane, auto filter and per-column formats. Mapping uses compiled accessors with no boxing.

public sealed class Order
{
    [ExcelColumn("Order #", Order = 0, Width = 10)]
    public int Id { get; init; }

    public string Customer { get; init; } = "";

    [ExcelColumn(NumberFormat = "yyyy-mm-dd")]
    public DateOnly Date { get; init; }

    [ExcelColumn(NumberFormat = "#,##0.00")]
    public decimal Amount { get; init; }

    [ExcelIgnore]
    public string InternalNote { get; init; } = "";
}

await writer.WriteWorksheetAsync("Orders", orders);                 // new sheet, header + filter + widths
await sheet.WriteObjectsAsync(moreOrders, new ObjectWriteOptions   // append to an existing sheet
{
    WriteHeader = false,
});

Supported member types: string, all integer types, float, double, decimal, bool, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan, Guid, enums (written as names), char, nullable versions of all of these, and any other type via ToString().

Tables, row grouping and auto-fit#

Excel tables#

AddTable turns a range into an Excel table (a ListObject), with a header row, filter buttons, banded rows and names you can use in formulas such as =SUM(Orders[Units]):

var sheet = writer.AddWorksheet("Orders");
await sheet.AddRowAsync("Product", "Units");
await sheet.AddRowAsync("Widget", 3);
await sheet.AddRowAsync("Gadget", 5);

sheet.AddTable(new ExcelTable(1, 1, sheet.RowNumber, 2)
{
    Name = "Orders",                    // optional: Table1, Table2, … otherwise
    Columns = ["Product", "Units"],     // must match the header row
    Style = TableStyle.Medium(9),       // Light(1–21), Medium(1–28), Dark(1–11) or None
});

With a header row (the default), Columns must list the header texts exactly as written, because Excel identifies table columns by those names. Table names are unique in the workbook and follow Excel’s name rules. Tables cannot overlap each other, merged cells or the worksheet auto filter. The range may include rows you have not written yet.

Row grouping#

Rows can be grouped into collapsible outline levels. Declare the deepest level when you add the worksheet, because Excel reads it before the rows:

var sheet = writer.AddWorksheet("Regions", new WorksheetOptions
{
    RowOutlineLevels = 1,           // deepest level used, 0–7
    OutlineSummaryAbove = true,     // the group's button sits on the row above it
});

await sheet.AddRowAsync("North", 300);
sheet.BeginRow(new RowOptions { OutlineLevel = 1 });                  // AddRow fills the begun row
await sheet.AddRowAsync("Store A", 120);

sheet.BeginRow(new RowOptions { OutlineLevel = 1, Hidden = true });   // a collapsed group's rows are hidden
await sheet.AddRowAsync("Store B", 180);

RowOptions also sets Height, Style and Collapsed (on the summary row of a collapsed group).

Auto-fit columns#

Turn on AutoFit and columns without an explicit width are sized to their content:

var sheet = writer.AddWorksheet("Orders", new WorksheetOptions { FrozenRows = 1 }.AutoFitColumns());

// Or tune the sample and cap the width (in characters):
new WorksheetOptions { AutoFit = new AutoFitOptions { SampleRows = 500, MaxWidth = 60 } };

Column widths come before the cell data in the file, so the writer holds back the sheet’s XML while it measures the first SampleRows rows (1,000 by default). It then writes the widths and streams the rest as usual. Memory is bounded by the sample: at most SampleRows rows or 8 MiB of XML, whichever comes first. Rows after the sample are not measured.

Widths are estimated from the text, the number format (dates, #,##0.00, percentages, …) and the font size and weight of each cell. Formulas and blank cells are not measured. Widths you set with SetColumn / SetColumnWidths always win.

Reading#

XlsxReader streams the rows of a worksheet. Open a file path or a seekable Stream, pick a worksheet by name or index, and call Read() until it returns false:

using Hypaxel;

using var reader = XlsxReader.Open("orders.xlsx");     // or new XlsxReader(stream, options)
Console.WriteLine(string.Join(", ", reader.SheetNames));

using var rows = reader.OpenWorksheet("Orders");        // or OpenWorksheet(0)
while (rows.Read())
{
    var row = rows.Row;                                 // reused for every row; Number is the 1-based Excel row
    if (row.TryGetString(1, out var customer)           // by 1-based column
        && row.TryGetDouble(3, out var amount)
        && row.TryGetDateTime(4, out var placed))
    {
        Console.WriteLine($"{row.Number}: {customer} {amount} {placed:yyyy-MM-dd}");
    }

    foreach (var cell in row.Cells)                     // only cells with a value, in column order
    {
        switch (cell.Value.Kind)
        {
            case ExcelValueKind.String: /* cell.Value.TryGetString(...) */ break;
            case ExcelValueKind.DateTime: /* cell.Value.TryGetExcelDateTime(...) */ break;
        }
    }

    ExcelValue[] dense = row.GetValues();               // columns 1..LastColumn, ExcelValue.Empty for gaps
}

// WorksheetReader is also an IEnumerable<XlsxRow>:
foreach (var row in reader.OpenWorksheet(1)) { /* ... */ }

Values#

ExcelValue is a small readonly struct with a Kind (Empty, String, Number, Boolean, DateTime, Error) and the accessors TryGetString, TryGetDouble, TryGetBoolean, TryGetDateTime, TryGetExcelDateTime and TryGetError.

Numbers whose built-in or custom number format shows a date, time or duration become ExcelDateTime: the raw Serial, its Kind (Date, DateTime, Time, Duration), Is1904, and TryGetDateTime, TryGetDateOnly, TryGetTimeOnly and TryGetTimeSpan. Both date systems are supported, including Excel’s fictitious 1900-02-29 (serial 60 has no DateTime). Times are rounded to the millisecond. ToString() gives roughly Excel’s General format, with dates in ISO 8601.

Formulas yield their cached result. A formula that was never calculated has no value.

Not read yet: formula text, styles beyond date detection, merged ranges, comments, hyperlinks and data validation.

Allocations and memory#

Numbers, booleans, dates and shared strings are read without allocating. Inline strings allocate when you ask for a string (TryGetString, GetValue, Cells). row.TryGetText(column, out ReadOnlySpan<char>) reads any text without allocating, and row.GetValues(Span<ExcelValue>) fills a reused array.

Rows are decompressed and parsed as a stream. What stays in memory is the shared string table (text that Excel stores once per workbook, held as strings) plus the current row. See Reading performance for measured peaks.

Sheets#

reader.Sheets lists every sheet with its Visibility (Visible, Hidden, VeryHidden) and Kind (Worksheet, Chartsheet, Other). OpenWorksheet(name) matches the name exactly first, then ignoring case. Several worksheets of one reader can be open at once on one thread. Use one reader per thread to read in parallel.

Compatibility#

The reader is tested with workbooks from the Hypaxel writer and the Open XML SDK, and with handcrafted packages that cover what other producers do: package relationships instead of fixed paths, Strict Open XML, prefixed namespaces, cells and rows without references, out-of-order and duplicate cells (the last one wins), rich text, inline strings, phonetic runs (skipped), ISO 8601 dates (t="d"), CDATA, CRLF line endings and Excel’s _xHHHH_ escapes.

Untrusted input and errors#

  • DTDs are rejected, so there is no entity expansion.
  • Every XML token (16 MiB) and row (16,384 cells, 128 Mi characters of text) is bounded.
  • ZIP entries must match their declared size and CRC-32.
  • XlsxReaderOptions.MaxSharedStringsBytes (default 1 GiB) caps the shared string table. Lower it for untrusted uploads.

Damaged or malicious input throws XlsxReadException (or an IOException from your stream), never another exception type. Its Kind is one of:

KindMeaning
InvalidFileNot an .xlsx: CSV, legacy .xls, a password-protected workbook, a Word file
MalformedA damaged part. Part names it, and the message names the row
LimitExceededThe input exceeds a configured or built-in safety limit
UnsupportedThe workbook uses a feature the reader does not support, such as an encrypted ZIP entry or a chart sheet
var options = new XlsxReaderOptions { MaxSharedStringsBytes = 64L * 1024 * 1024 };

Streams and large files#

The input must be seekable, because the ZIP directory is at the end of the file. Copy a non-seekable stream, such as a raw request body, into a MemoryStream or a temporary file first. Reading is synchronous.

For a large single file, new XlsxReaderOptions { BackgroundDecompression = true } inflates on a second thread and reads about 30% faster when cores are idle. Leave it off for many concurrent reads: when every core is busy, it makes the total slower. See Reading performance.

Options#

new XlsxWriterOptions
{
    CompressionLevel = CompressionLevel.Fastest,  // or Optimal for smaller files
    StringStorage = StringStorage.Inline,         // or SharedStrings for repetitive text
    FlushThreshold = 64 * 1024,                   // bytes buffered before an async write
    WriteCellReferences = false,                  // true = r="A1" on every cell
    Use1904DateSystem = false,
    OwnsStream = false,
};

The writer accepts any writable Stream (seekable or not) and also has a file path helper. Both async and sync APIs are available.

Notes and limits#

  • Write order: rows are written top to bottom, and cells left to right. Use SkipCells / SkipRows / BeginRow(n) to leave gaps.
  • One worksheet at a time: adding the next worksheet completes the previous one.
  • Options up front: column definitions, frozen panes and the outline depth go in WorksheetOptions when you create the sheet, because they come before the cell data in the file. Merges, filters and tables can be added at any time before the sheet completes.
  • Formulas are stored without cached results. Excel recalculates them when the file opens.
  • Dates: 1900 and 1904 date systems. Unstyled dates get the viewer’s locale date format. Dates before 1900 are written as ISO text.
  • Values: NaN and infinity are written as #NUM!.
  • Strings: inline by default, or a shared string table. Full XML escaping, control characters as _xHHHH_, lone surrogates replaced.
  • Reading: the reader’s input must be a seekable stream, and reading is synchronous. See Reading.
  • BeginRow(null): since 0.2.0, sheet.BeginRow(null) with a literal null no longer compiles because it is ambiguous with the BeginRow(RowOptions) overload.

Performance#

On an Apple M1 Max, Hypaxel writes 1 million rows × 10 columns in about 0.8 s on .NET 9 and later (about 1.2 s on .NET 8), with less than 1 MB allocated. It is within measurement noise of SpreadCheetah and roughly 20 to 25 times faster than ClosedXML, which also allocates far more memory. Memory per concurrent export is bounded by the buffers: about 64 KiB of XML plus about 96 KiB of compressed output by default.

.NET: 100,000 rows, mean timeApple M1 Max, 10 cores, macOS 26.6; .NET 8.0.34, 9.0.23, 10.0.15 and 11.0.0. Compared with SpreadCheetah 1.29.0, ClosedXML 0.105.1, BenchmarkDotNet 0.15.8.
.NET 10lower is better
  1. Hypaxel, typed Write78 ms, best
  2. Hypaxel, AddRowAsync76 ms, best
  3. Hypaxel, object mapping80 ms, 1.1×
  4. Hypaxel, shared strings89 ms, 1.2×
  5. SpreadCheetah75 ms, best
  6. ClosedXML1,845 ms, 25×
.NET: 100,000 rows, mean time
Case.NET 8.NET 9.NET 10.NET 11
Hypaxel, typed Write122 ms78 ms78 ms74 ms
Hypaxel, AddRowAsync127 ms87 ms76 ms75 ms
Hypaxel, object mapping118 ms78 ms80 ms75 ms
Hypaxel, shared strings159 ms97 ms89 ms90 ms
SpreadCheetah123 ms79 ms75 ms74 ms
ClosedXML2,369 ms1,910 ms1,845 ms1,773 ms

Methodology and notes · Benchmark source

.NET: 100,000 rows, allocated memoryApple M1 Max, 10 cores, macOS 26.6; .NET 8.0.34, 9.0.23, 10.0.15 and 11.0.0. Compared with SpreadCheetah 1.29.0, ClosedXML 0.105.1, BenchmarkDotNet 0.15.8.
.NET 10lower is better
  1. Hypaxel, typed Write12 KB, best
  2. Hypaxel, AddRowAsync12 KB, best
  3. Hypaxel, object mapping15 KB, 1.3×
  4. Hypaxel, shared strings10.1 MB, 842×
  5. SpreadCheetah16 KB, 1.3×
  6. ClosedXML1,103 MB, 91917×
.NET: 100,000 rows, allocated memory
Case.NET 8.NET 9.NET 10.NET 11
Hypaxel, typed Write208 KB12 KB12 KB14 KB
Hypaxel, AddRowAsync208 KB12 KB12 KB14 KB
Hypaxel, object mapping212 KB15 KB15 KB17 KB
Hypaxel, shared strings11 MB10.1 MB10.1 MB10.1 MB
SpreadCheetah84 KB15 KB16 KB18 KB
ClosedXML1,190 MB1,098 MB1,103 MB1,087 MB

Methodology and notes · Benchmark source

.NET: 1,000,000 rows, timeApple M1 Max, 10 cores, macOS 26.6; .NET 8.0.34, 9.0.23, 10.0.15 and 11.0.0. Compared with SpreadCheetah 1.29.0.
.NET 10lower is better
  1. Hypaxel, typed Write0.78 s, best
  2. Hypaxel, AddRowAsync0.77 s, best
  3. Hypaxel, object mapping0.81 s, 1.1×
  4. Hypaxel, shared strings1 s, 1.3×
  5. SpreadCheetah0.76 s, best
.NET: 1,000,000 rows, time
Case.NET 8.NET 9.NET 10.NET 11
Hypaxel, typed Write1.21 s0.8 s0.78 s0.73 s
Hypaxel, AddRowAsync1.23 s0.83 s0.77 s0.76 s
Hypaxel, object mapping1.26 s0.82 s0.81 s0.75 s
Hypaxel, shared strings1.42 s1.12 s1 s0.99 s
SpreadCheetah1.41 s0.85 s0.76 s0.74 s

Methodology and notes · Benchmark source

See Performance for methodology and reproduction, and Benchmarks for the full tables.

Reading performance#

On the same 1 million rows × 10 columns, read cell by cell, XlsxReader takes about 0.75 to 0.85 s, or about 0.55 s with background decompression. That is about 2.4 times faster than Sylvan.Data.Excel, about 5.5 times faster than ExcelDataReader and 9 to 15 times faster than MiniExcel. Every reader in the comparison produces the same checksum over all cells.

Reading text as a span allocates almost nothing on a file with inline strings. With shared strings, the table itself (92 MB for 1 million distinct strings) is what stays in memory. Nothing else grows with the number of rows, because the row buffers are sized by the widest row.

.NET reading: 1,000,000 rows, timeApple M1 Max, 10 cores, 64 GB, macOS 26.6; .NET 8.0.19, 9.0.0, 10.0.13 and 11.0.0. Compared with Sylvan.Data.Excel 0.5.8, ExcelDataReader 3.9.0, MiniExcel 1.47.1.
.NET 10lower is better
  1. Hypaxel, TryGetText/TryGetDouble (inline)0.76 s, 1.5×
  2. Hypaxel, GetValue/ExcelValue (inline)0.8 s, 1.5×
  3. Hypaxel, BackgroundDecompression (inline)0.52 s, best
  4. Sylvan.Data.Excel (inline)1.87 s, 3.6×
  5. ExcelDataReader (inline)4.26 s, 8.2×
  6. MiniExcel (inline)6.94 s, 13×
  7. Hypaxel, TryGetText/TryGetDouble (shared)0.81 s, 1.6×
  8. Hypaxel, GetValue/ExcelValue (shared)0.83 s, 1.6×
  9. Hypaxel, BackgroundDecompression (shared)0.56 s, 1.1×
  10. Sylvan.Data.Excel (shared)1.92 s, 3.7×
  11. ExcelDataReader (shared)4.4 s, 8.5×
  12. MiniExcel (shared)12.49 s, 24×
.NET reading: 1,000,000 rows, time
Case.NET 8.NET 9.NET 10.NET 11
Hypaxel, TryGetText/TryGetDouble (inline)0.74 s0.8 s0.76 s0.73 s
Hypaxel, GetValue/ExcelValue (inline)0.82 s0.86 s0.8 s0.79 s
Hypaxel, BackgroundDecompression (inline)0.59 s0.56 s0.52 s0.51 s
Sylvan.Data.Excel (inline)2.19 s2.04 s1.87 s1.94 s
ExcelDataReader (inline)5.24 s4.82 s4.26 s4.6 s
MiniExcel (inline)9.24 s8.1 s6.94 s7.28 s
Hypaxel, TryGetText/TryGetDouble (shared)0.8 s0.86 s0.81 s0.82 s
Hypaxel, GetValue/ExcelValue (shared)0.87 s0.89 s0.83 s0.85 s
Hypaxel, BackgroundDecompression (shared)0.64 s0.6 s0.56 s0.58 s
Sylvan.Data.Excel (shared)2.18 s2.07 s1.92 s1.99 s
ExcelDataReader (shared)5.29 s4.88 s4.4 s4.64 s
MiniExcel (shared)14.77 s13.71 s12.49 s12.84 s

Methodology and notes · Benchmark source

.NET reading: 1,000,000 rows, memoryApple M1 Max, 10 cores, 64 GB, macOS 26.6; .NET 10.0.13. Compared with Sylvan.Data.Excel 0.5.8, ExcelDataReader 3.9.0, MiniExcel 1.47.1.
Inline: peak RSSlower is better
  1. Hypaxel, TryGetText/TryGetDouble49 MB, best
  2. Hypaxel, GetValue/ExcelValue55 MB, 1.1×
  3. Hypaxel, BackgroundDecompression51 MB, best
  4. Sylvan.Data.Excel75 MB, 1.5×
  5. ExcelDataReader77 MB, 1.6×
  6. MiniExcel81 MB, 1.7×
.NET reading: 1,000,000 rows, memory
CaseInline: allocatedInline: peak RSSShared: allocatedShared: peak RSS
Hypaxel, TryGetText/TryGetDouble0.1 MB49 MB92 MB141 MB
Hypaxel, GetValue/ExcelValue153 MB55 MB92 MB141 MB
Hypaxel, BackgroundDecompression0.6 MB51 MB92 MB137 MB
Sylvan.Data.Excel154 MB75 MB85 MB156 MB
ExcelDataReader1,937 MB77 MB1,717 MB158 MB
MiniExcel10,649 MB81 MB10,157 MB84 MB

Methodology and notes · Benchmark source

.NET reading: background decompressionApple M1 Max, 10 cores, 64 GB, macOS 26.6; .NET 10.0.13. Compared with .
Timelower is better
  1. Default, one reader (inline)0.77 s, 1.5×
  2. BackgroundDecompression, one reader (inline)0.53 s, best
  3. Default, one reader (shared)0.83 s, 1.6×
  4. BackgroundDecompression, one reader (shared)0.58 s, 1.1×
.NET reading: background decompression
CaseTimeCPU time
Default, one reader (inline)0.77 s0.76 s
BackgroundDecompression, one reader (inline)0.53 s0.92 s
Default, one reader (shared)0.83 s0.84 s
BackgroundDecompression, one reader (shared)0.58 s0.97 s

Methodology and notes · Benchmark source

The reader is fast because it uses a purpose-built UTF-8 pull parser instead of System.Xml.XmlReader, matches the common cell shapes with their attributes in a single scan, parses numbers, shared-string indexes and booleans straight from the input buffer, and reuses its row buffers. It verifies CRC-32 itself, with the ARM64 CRC instructions where available.

Building from source#

The source is at github.com/vensas/hypaxel, in the dotnet/ directory. Report bugs at github.com/vensas/hypaxel/issues.

cd dotnet
dotnet build
dotnet test
dotnet run --project samples/Hypaxel.Samples.WebApi -f net10.0   # GET /orders.xlsx, /report.xlsx, /api/export