Skip to content

feat(core): make table Excel exports look like the table (ExcelJS → hucre) - #3358

Closed
nickfanion wants to merge 5 commits into
evidence-dev:mainfrom
nickfanion:feat/excel-export-hucre
Closed

nickfanion wants to merge 5 commits into
evidence-dev:mainfrom
nickfanion:feat/excel-export-hucre

Conversation

@nickfanion

@nickfanion nickfanion commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Downloading a table to Excel now gives a sheet that looks like the table on the page, so nobody has to reformat it, fit columns, or rebuild totals by hand, and it still behaves like a real spreadsheet: numbers and dates stay native values, nothing is merged, and formats are Excel number formats rather than text.

It also replaces ExcelJS with hucre.

What a table export looks like now

Table feature In the Excel sheet
Title / subtitle Bold title, muted subtitle. Not counted when autofitting columns
Column groups, pivot headers, measures-first headers One header row per level. Group labels use Center Across Selection with a Single Accounting underline instead of merged cells
Header row Bold, with the same rule underneath. Titles wrap the way the page wraps them: a table too wide for a default-width page narrows its columns toward their data and wraps the titles, instead of widening each column to fit its title. wrap_titles and format_titles are honored
Sorting by a column header Rows export in the order shown on screen
Totals and subtotals Same fills, bold text, and rule above as on screen. Pivot total/subtotal columns are tinted
row_lines, row_shading Row borders in the theme's row-border color, alternating shading. Gridlines are off
Repeated dimension values (subtotaled tables) Shown on the first row of each group, as on screen, without merged cells. repeat_values (table or dimension) repeats them
collapsible / collapsed Excel outline groups, in the same expanded/collapsed state as the page, with subtotals above their rows
viz="bar" Excel conditional-format data bars: solid fill on the same scale as the screen (including scale_mode="shared" across pivot columns), red negative bars from a zero axis, plus bar_color, bar_color_negative, fit_to_data, hide_labels, and viz_include_subtotals
viz="color", color_scale, color_stops, midpoint, conditional_colors, row_conditional_colors Static cell fills, text colors, and borders computed by the same code as the screen (see below for why this isn't conditional formatting)
viz="delta" Green/red/gray text from the same rules (down_is_good, neutral_range). Negative values keep their minus sign
red_negatives Negative values in the theme's negative color
viz="sparkline" Native Excel sparklines (bar → column; line and area → line) in the theme's color. The series lives in hidden columns next to the table
fmt, fmt_column, comparison pct_fmt/abs_fmt, auto formats (usd, num, pct) Excel number formats with the same per-column unit and decimals as the screen (e.g. $1.2M). Zero drops the unit, as on screen. Dates are real Excel dates
freeze_columns Frozen columns. The header rows are frozen too, like the table's sticky header
align, wrap Cell alignment and wrap text. Rows grow to fit wrapped text
link Clickable hyperlinks in the theme's link color. Report-relative links resolve to absolute URLs, and only http(s), mailto, and tel links are written
html The HTML's text content
hide, row link column Left out, as on screen
Theme Light-theme colors from the report's theme (table backgrounds, borders, bar, positive/negative, color scale), including card surfaces

Across the workbook:

  • The font is Calibri 11 (see Why Calibri below).
  • Columns are autofit with real Calibri metrics, from the header and data only.
  • Table rows are 18 pt, like the table's rows. Each row has its own height, because Excel for Windows re-measures rows that only have the sheet's default height.
  • Each column's default format is its alignment and number format, so data typed below the table picks them up.
  • Printing repeats the header rows on every page and fits the table to one page wide.

The page-level Excel exports use the same sheets. Both Download Data and Generate Excel Report now write each table the way it renders (pivoted, with totals and formatting) instead of its unpivoted query results. Other components (charts etc.) get a plain data sheet with the same base styling. The single-component downloads for charts and the download component get that base styling too.

Deliberate differences from the screen

Some on-screen behavior has no faithful Excel equivalent, or copying it would make the file worse to work with:

  • Color scales are static fills, not conditional formatting. Evidence's scales (multi-stop palettes, color_stops, midpoint, scale columns, per-row conditional colors, background-anchored single colors) don't map onto Excel's 2- and 3-color scales. Static fills match the screen exactly.
  • Data bars are conditional formatting. Excel's data bars do match Evidence's bars, so the bar redraws if a value changes.
  • No delta chevrons. The ▲/▼ glyphs are dropped and the color stays. A chevron inside a number format can't respect neutral_range, and Excel's icon sets can't recolor for down_is_good. Negative values show a minus sign.
  • Merged dimension cells show the value on the first row of the group rather than as a merged cell. Merged cells break sorting, filtering, selection, and copy/paste. This is also how Excel's own PivotTables lay out tabular rows.
  • Empty cells are blank, not "–", so numeric columns stay numeric for formulas.
  • Header text is bold. The screen uses medium weight, which Excel doesn't have.
  • Images and logos export as their label text. Fetching third-party images at export time would be slow and often blocked by CORS.
  • Stripes in collapsible tables follow the fully expanded table, so they still alternate after groups are expanded in Excel.
  • Titles wrap as they would on a default-width page. The file comes out the same whatever the window size, so on a page_width: full page in a wide window, a medium-width table can wrap titles in Excel that fit on one line on screen.
  • Tooltips (info and comparison tooltips) and the row-link chevron column are left out. Tooltips aren't formatting, so they're outside this change, and the chevron column has no Excel equivalent.

Why hucre instead of ExcelJS

  • Maintained. ExcelJS's last stable release was 4.4.0 in October 2023, and it has ~820 open issues. hucre is actively released (1.3.0, October 2026), MIT-licensed, and has thorough read/write parity docs and tests.
  • Zero dependencies. Removing ExcelJS drops ~50 transitive packages from the lockfile, including archiver, jszip, unzipper, tmp, saxes, and fast-csv. Two of them already needed security overrides in the root package.json (unzipper, uuid); unzipper was only there for ExcelJS.
  • Smaller, and off the page bundle. ExcelJS's browser build is 948 KB minified (258 KB gzipped) and was imported statically. hucre's writer is 152 KB minified (48 KB gzipped), and it's now loaded with a dynamic import() on the first export.
  • Browser-first. hucre uses only Web APIs (no Node streams or Buffer polyfills) and ships complete TypeScript types.
  • Covers what this needs: Center Across Selection, accounting underlines, conditional formatting, sparklines, outline groups, freeze panes, print titles, and a workbook default font.
  • About twice as fast, while producing a fully formatted sheet (see Performance below).

In fairness, ExcelJS already writes Excel 2010 data bars (solid fill, negative bars); hucre 1.3.0 only writes the 2007 kind (gradient, 10–90% length, no zero axis). This PR closes that gap with a small patch (below), which I plan to upstream.

Performance

Exporting is about twice as fast as before for tables of 20,000 rows or more.

Table (rows × 10 columns) Before (ExcelJS) After (hucre) Speedup
1,000 47 ms 35 ms 1.4×
20,000 922 ms 433 ms 2.1×
100,000 4.75 s 2.37 s 2.0×

How this was measured:

  • Both versions ran on the same machine (Apple M3 Pro, Node 24, which uses the same V8 engine as Chrome) with the same synthetic table: two dimensions, eight measures with auto and fixed formats, a bar column, a color column, and a total row.
  • "Before" is main's export pipeline: buildTableExcelExportColumns, getCellStyle, addDataToWorksheet, then writeBuffer. "After" is buildTableExcelSheet plus writeWorkbook.
  • The download step is excluded from both. Each figure is the median of 5 runs after a warm-up.

Where the time goes:

  • Writing the file is 3–4× faster with hucre (860 → 225 ms at 20,000 rows).
  • Building the sheet is slower (61 → 208 ms), because the new export does work the old one skipped. It formats every value the way the report does, sizes every column from its content rather than the first 10 rows, and computes bars, color scales, borders and fills.
  • File size grows by about 4% for that formatting.

To keep the build fast:

  • Only each column's widest numbers are formatted to size it. Digits share one width, so the largest and most-negative values are the widest; formats where that doesn't hold are still measured cell by cell.
  • Color styles are cached by color.
  • Identical cells share one style object, which hucre deduplicates by identity.

The first export also downloads hucre's writer once: about 48 KB gzipped, previously part of the page bundle.

How formatting is applied

An .xlsx file has no range-level formatting. Each distinct combination of font, fill, border, alignment and number format is stored once in the workbook's style table, and each cell points at one entry. That is also how Excel saves a range you format by hand.

The QA tables use 8–22 distinct formats each; a 200,000-cell table with a color scale uses about 460, almost all of them its gradient's colors. Formatting is applied at the broadest level Excel allows without spilling past the table:

  • Columns carry their alignment and most common number format as the column's default format. Cells that match it are written as plain values with no format of their own, and data typed below the table inherits it.
  • Cells carry only what varies: row lines and the rules above totals, fills (totals, subtotals, shading, color scales), bold, text colors, and number formats that differ from the column's, such as zero dropping its unit.

Borders and fills can't move up to columns or rows. A column's default format applies to every row of the sheet, and a row's to every column, so a border or fill set there would run past the table's edges.

Why Calibri

  • It was Excel's default font for about 15 years, from Office 2007 until Microsoft 365 moved to Aptos Narrow, so every Office install has it.
  • Where it isn't installed, ChromeOS and LibreOffice substitute Carlito, which has identical metrics, so column widths and wrapping still fit.
  • Aptos Narrow is too new to rely on: older Office versions and other spreadsheet apps don't have it.
  • The export's width calculations use Carlito's open-licensed (OFL) metrics.
  • Fonts are a parameter (ExcelFont), so the export font can be made configurable later without touching the layout code.

The hucre patch (patches/hucre@1.3.0.patch)

The patch is applied through pnpm patchedDependencies, like the existing ssf/echarts/zrender patches, and is listed in patches/THIRD-PARTY-NOTICES.md. It touches only the worksheet writer and its types, with every change marked [MODIFIED]:

  • Data bars: optional Excel 2010 settings (gradient, minLength/maxLength, border, negativeFillColor, axisPosition, axisColor, direction) plus showValue. Setting any of them writes the rule's x14 extension, the same structure Excel writes. Readers that don't understand it fall back to the 2007 bar.
  • Sparklines: displayHidden (plot data in hidden columns) and manualMin (pin the axis minimum, so sparklines include zero like the report's).

Other changes

  • Shared display rules. The rules the table template used inline are now shared helpers, used by both the template and the export so they can't drift:
    • cell emphasis for totals, subtotals, and pivot columns;
    • color-viz eligibility and borders;
    • cell format and link resolution;
    • header titles;
    • sparkline parsing;
    • delta status, which DeltaDisplay uses too.
  • formatValue's format-code resolution (auto units, zero handling) is extracted as resolveFormatCode, so Excel number formats follow the same rules.
  • resolveTableColors is exported from the theme CSS helper, so the export reads the same table colors the CSS variables get.
  • Export font. Fonts are an ExcelFont (name, size, line height, glyph metrics). Each export picks its font once (getExcelExportFont()) and passes it to every sheet builder and to the writer, so widths are always measured in the font the workbook declares. Supporting another font later means adding its metrics.
  • Robustness:
    • A table export that fails shows a toast instead of failing silently.
    • In page exports, a table whose styled sheet fails falls back to its raw data.
    • Hyperlinks are capped at Excel's 65,530-per-sheet limit.
    • 64-bit IDs beyond 2^53 are written as exact text.
    • Translucent theme colors are blended over white.
  • Download filenames are made valid on every OS. Slashes in titles such as "52W 10/4/26" become hyphens instead of whatever character each browser substitutes. This applies to CSV downloads too.
  • Docs. features/page-settings.mdx now describes what table sheets contain.

Testing

  • Unit tests. 85 tests cover the export. The ExcelJS tests were translated to hucre, and tests read written workbooks back with hucre and assert on the raw XML where it matters (x14 data bars, sparkline ranges). The full core suite passes. The one failure, waterfall_chart.test.ts's date-range snapshot, fails on main too: it depends on the machine's timezone and passes with TZ=UTC.
  • Real Excel. Every scenario was exported from the running CLI (cli/test-environment/pages/excel-export.md, one table per feature group), then checked three ways:
    • validated against the ECMA-376 XSD schemas;
    • parsed with openpyxl;
    • opened in Microsoft Excel for Mac with no repair prompts, and saved to PDF to compare with the page. The same was done for the page-level export.
  • Excel for Windows. All of the QA files were also opened in Excel for Windows, where they render and behave correctly. That check caught a long table's rows shrinking partway down, which is fixed by giving every row an explicit height.
  • Sorting. A pivot table and a subtotaled table were sorted by clicking a column header, and the exported rows matched the order on screen.
  • A real report. A production report table was exported the same way and opened in Excel: 223 rows × 27 columns, with column groups, bars with custom and negative colors, deltas, a color scale, a frozen column, the total row on top, and conditional row highlighting.
  • A second real report. A distribution grid pivoted over 40 retailer and market names (76 rows × 41 columns, color-scale cells) was exported and opened in Excel. It showed that titles under 200px never wrapped, which made each column two to three times its width on the page. Titles now wrap as they do on the page (before and after in the comments). After that change, the ten QA tables were exported with both the old and the new code: column widths and row heights are identical, and only the header row's vertical alignment changed.
  • Type and format checks. svelte-check for core passes with no errors, and the changed files are prettier-clean. The CLI check's only error is the generated docs bundle, which needs a bun build.

Not verified:

  • Excel on the web.
  • LibreOffice, Google Sheets, and Numbers, which may render the Excel 2010 data-bar extension and Center Across Selection differently.
  • Exports beyond the 1-million-cell benchmark (100,000 rows × 10 columns).
  • Server-side-paginated tables still export only the loaded rows, as before.

Follow-ups

  • Upstream the hucre data-bar and sparkline options, then drop the patch.
  • The root unzipper override no longer applies to anything and could be removed.

🤖 Generated with Claude Code

https://claude.ai/code/session_01S5uhmnLon3oEE2M1VKKZ4L

nickfanion and others added 3 commits November 1, 2026 14:46
…hucre)

Table downloads now produce a sheet laid out like the rendered table while
staying a working spreadsheet: multi-level headers (Center Across
Selection with a Single Accounting underline), totals and subtotals,
row lines and shading, Excel 2010 data bars, static color-scale fills,
colored deltas, red negatives, links, native sparklines, frozen columns
and header, collapsible groups as outline groups, Calibri 11, and autofit
columns. Numbers and dates stay native with the report's number formats.

The page-level Download Data and Generate Excel Report exports use the
same styled sheets for tables; other components get a plain styled
data sheet.

ExcelJS is replaced by hucre (zero dependencies, ~48 KB gzipped, loaded
on first export), patched to write Excel 2010 data-bar options and two
sparkline options. Exports are about twice as fast for 20k+ row tables.

Display rules the table template used inline are now shared helpers used
by both the template and the export. Download filenames are made valid
on every OS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S5uhmnLon3oEE2M1VKKZ4L
One table per group of table options that change how a table looks, for
checking table Excel exports by hand against the rendered page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S5uhmnLon3oEE2M1VKKZ4L
Excel for Windows re-measures a row that has content but no height of its
own, ignoring the sheet's default row height, so a long table's rows shrank
from 18pt to the font's natural height partway down. Header and body rows
now carry an explicit height, as wrapped rows already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S5uhmnLon3oEE2M1VKKZ4L
@vercel

vercel Bot commented Nov 1, 2026

Copy link
Copy Markdown

@nickfanion is attempting to deploy a commit to the Evidence Team on Vercel.

A member of the Team first needs to authorize it.

@nickfanion

Copy link
Copy Markdown
Contributor Author

Some before/after screenshot examples:

01-pivot-with-totals-row-shading-and-a-frozen-column 02-two-dimensions-with-subtotals-bars-and-red-negatives 03-column-groups-and-sparklines 04-color-scales-and-conditional-colors 05-deltas-and-comparisons 06-collapsible-groups 07-measures-first-multiple-measures 08-dates-links-wrapping-hidden-labels-and-fit-to-data-bars 09-repeated-values

nickfanion and others added 2 commits November 2, 2026 08:34
Drops an unused type import from the table export and moves the
`downloadBlob` doc comment, which had ended up above `sanitizeFilename`,
back onto its function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Header titles only wrapped past 200px, so a wide table with short data
under longer titles (a pivot over 40 retailer names, say) exported every
title on one line, with columns two to three times their width on the
page.

Columns are now laid out the way the browser lays out the report's
table. Each one ranges from its data or its title's longest word to its
data or its whole title on one line. A table that fits in about the width
a default page gives it keeps its titles on one line, as before; a wider
one narrows its columns toward their data and wraps the titles, and the
header row grows to the tallest title. Bottom-row titles are
bottom-aligned, so shorter titles sit on the rule as they do on screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nickfanion

Copy link
Copy Markdown
Contributor Author

Update: exported headers now wrap the way the page wraps them

I tested the export on a second real report: a distribution grid pivoted over 40 retailer and market names. Its headers didn't wrap. Titles under 200px always stayed on one line, so each column widened to fit its name, and the geography columns came out about 4,600px wide against about 2,600px on the page.

fea07c3 lays the columns out the way the browser lays out the report's table. A table that fits on a default-width page keeps its titles on one line, as before. A wider one narrows its columns toward their data and wraps the titles. Bottom-row titles are now bottom-aligned too, so shorter titles sit on the rule as they do on screen.

distribution-grid-header-wrapping
  • Distribution grid: the geography columns are now about 2,530px wide, against about 2,560px on the page, and the titles wrap to 1–5 lines, as they do on the page. Checked in Excel for Mac.
  • The ten QA tables: I exported each one with the old and the new code. Column widths and row heights are identical; only the header row's vertical alignment changed.
  • Unit tests: five new tests cover a table that fits, one too wide for the page, one in between, a title longer than 200px, and wrap_titles=false.

a4808a1 also removes an unused import and moves a doc comment back onto its function.

@hughess

hughess commented Nov 3, 2026

Copy link
Copy Markdown
Member

/upstream

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Imported for internal review, this PR will be updated when it merges.

@hughess

hughess commented Nov 22, 2026

Copy link
Copy Markdown
Member

Thanks for the contribution, @nickfanion! Merged upstream, and synced back in 5e44dad

@hughess hughess closed this Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants