feat(xlsxgen): generate spreadsheets from a declarative spec and structured data

Abierto
#207 3 comentarios 0 reacciones 1 asignado Ver en GitHub

Los mantenedores suelen responder en 1 día

@sthanikan2000 ya está trabajando en esto.

Desde el 17/9/2026.

Evaluación

Este issue todavía no se ha evaluado.

Descripción

Type/New Feature

1. Problem

Core does not support generating spreadsheets. A single window system has to hand people tabular
output — a sales schedule, a line-item listing, a reconciliation — and there is no supported way to
produce a workbook from data the system already holds. archive/zip is used nowhere in the repo,
so this is greenfield.

Writing .xlsx by hand is not realistic. It is a ZIP of interdependent OOXML parts, and getting
the content types, relationships or cell encoding wrong produces a file Excel silently refuses to
open, usually with no useful diagnostic.

2. Proposed approach

A standalone module xlsxgen, stdlib-only (archive/zip + encoding/xml), mirroring
xmlgen's shape and dependency profile.

The template is a JSON spec, not a binary workbook. A spec describes the sheet, where the rows
come from, and how each column is headed and formatted:

{
  "sheet": "Auction Report",
  "rows": "sales.sheet",
  "columns": [
    { "header": "Date of Sale", "from": "Sale_date" },
    { "header": "Garden Mark",  "from": "Garden_mark" },
    { "header": "Rate per KG",  "from": "Sale_rate",     "type": "number", "format": "#,##0.00" },
    { "header": "Qty in KG",    "from": "Sale_quantity", "type": "number" },
    { "header": "Total Value",  "from": "Sale_value",    "type": "number", "format": "#,##0.00" }
  ]
}

At its smallest the spec is two fields — a sheet name and where the rows are:

{ "sheet": "Sales Data", "rows": "sales.sheet" }
Two row shapes

Tabular data reaches a generator in one of two forms, and the spec has to serve both:

// a matrix — row 1 is already the header
[["Date", "Item", "Qty"], ["01/06/2026", "Widget A", 500]]

// records — one object per row
[{ "Date": "01/06/2026", "Item": "Widget A", "Qty": 500 }]

They are told apart by whether the first element is an array.

  • Matrix, no columns given — written verbatim, header row included. This is the common case
    and needs no column spec at all.
  • Records — columns is required, supplying both the order and the header text. Not optional
    sugar: a decoded JSON object is a Go map, which has no iteration order, so without an explicit
    list the column order would vary between runs.
  • Matrix with columns given — columns select and re-order by position ("index": 2) rather
    than by field name, which also lets a caller drop or reorder columns of a matrix it does not own.
Interface

Deliberately the same shape as xmlgen, so the two read as siblings:

// Generate renders spec against data and returns the .xlsx bytes.
func Generate(ctx context.Context, spec []byte, data any, opts ...Option) ([]byte, error)

// GenerateTo is Generate writing to w. Like xmlgen's, it does not stream: a ZIP
// central directory can only be written once the whole archive is known, so w
// receives nothing unless the whole workbook is valid.
func GenerateTo(ctx context.Context, w io.Writer, spec []byte, data any, opts ...Option) error

// Validate checks a spec without data, for load-time and CI checks.
func Validate(spec []byte) error

func WithMaxOutputBytes(n int64) Option
func WithStrictKeys() Option   // a column whose `from` is absent becomes an error

data accepts the same inputs as xmlgen: []byte/json.RawMessage decoded internally with
UseNumber, or an already-decoded map[string]any. Output is bytes, never a file — the caller
streams it to a download or hands it to storage.

What it emits

Six OOXML parts, the minimum for a workbook that opens everywhere:

[Content_Types].xml, _rels/.rels, xl/workbook.xml, xl/_rels/workbook.xml.rels,
xl/worksheets/sheet1.xml, and xl/styles.xml only when a column declares a format.

Three decisions inside that, each of which is a trap if taken the other way:

  • Inline strings (<c t="inlineStr"><is><t>…</t></is></c>) rather than a shared-strings table.
    Marginally larger files, but it removes a whole part and its index-consistency failure mode.
  • Cell text is XML-escaped and control characters replaced, the same rule xmlgen enforces — a
    value containing & must not produce a workbook Excel refuses to open.
  • archive/zip records modification times, which would make output non-reproducible. Zeroing
    FileHeader.Modified keeps byte-stability, the property xmlgen already advertises so a
    generated artefact can be hashed or signed.
Values, not formulas

Aggregates are written as computed numbers rather than as =SUM(...). Common spreadsheet parsers
read a formula cell's cached value rather than its formula text, so a workbook carrying formulas
without cached results reads back empty — and computing the cache correctly means reimplementing a
formula engine. The cost is that a recipient editing a row in Excel sees no recalculation, which is
acceptable for a document that is a record rather than a working model.

Properties the output must hold

Worth pinning with tests, because each is easy to get subtly wrong and hard to notice:

  • one sheet, since many readers take the first and ignore the rest
  • the header in row 1, so the table is addressable as A1:…
  • blank cells omitted entirely rather than written as empty strings, so a reader can distinguish
    "no value" from ""
  • numbers written as numbers, not as text that looks numeric
  • the file unzips, every declared part exists, and the sheet XML parses
Not in scope

Styling beyond number formats, charts, images, merged cells, frozen panes, multiple sheets,
formulas, and .xlsm. Each of those is a reason to reach for github.com/xuri/excelize/v2 — which
would make xlsxgen the first pure-computation module in core carrying a large third-party
dependency, against the precedent of xmlgen, httputil and shared, all of which have none. If
a styled workbook is ever genuinely required, adding an excelize-backed path behind the same
interface is the follow-up, not a reason to start there.

3. Open decisions

  1. Aggregates. A table often arrives alongside computed totals. Should the spec place them — as
    a trailing totals row, a separate block below the table, or left to the caller to fold into the
    rows first? A trailing row is the obvious default but complicates the "rows come from one path"
    model.
  2. Dates. Write them as strings, or as real Excel date serials with a numFmt? Serials are
    what makes a date sortable and formattable in Excel; strings are simpler and survive any reader
    unchanged. This changes what downstream code has to handle, so it is worth deciding once.
  3. Transposed output. A "wide" table puts labels in column A and one record per subsequent
    column. Worth supporting on the write side, or is row-per-record enough?
  4. Where the spec lives. artifact.Loader returns raw []byte, so a spec could be a registry
    artifact with its own adapter — the same follow-up pending for XML templates.
  5. CSV. Is a CSV writer wanted from the same module, or is that a separate concern?
Lenguaje dominante
Go
Estrellas
6
Forks
8
Merge medio
21 h 36 min
PR fusionados (30 d)
42

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de OpenNSW/core

Todos los issues de OpenNSW/core

Issues similares

Más issues de Go

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.