# Tables

Spreadsheets in and out: `csv` reads and writes CSV (and TSV, and the
other delimiters people use), `xlsx` reads and writes Excel workbooks.
Both work on a page and in a `server fn`, give plain rows or rows typed
into a shape, and say where a cell is when it is not what the shape wants.
Back to the [map](README.md).

```mote
// docs: whole
shape Order
  item: string
  price: number
  when: time?
  paid: bool

state orders: Order[] = []
state said = ""

action open
  let f = fs.pick(".csv,.xlsx")?
  if f == none return
  orders = f.name.endsWith(".xlsx") ? xlsx.records(f.data, Order)? : csv.records(f.data, Order)?
  said = `${orders.length} orders`

action export
  let book = xlsx.write([{name: "Orders", rows: orders, columns: [{key: "item", title: "Item"}, {key: "price", title: "Price", format: "currency"}, {key: "when", title: "When", format: "date"}, {key: "paid", title: "Paid"}], filter: true}])?
  fs.save(book, "orders.xlsx")?

column gap=8 padding=16
  row gap=8
    button "Open a CSV or workbook" press=open
    button "Save as .xlsx" press=export disabled=(orders.length == 0)
  text (failure(open) ?? said) color=dim
  for o in orders
    text `${o.item}: ${o.price}${o.paid ? ", paid" : ""}`
```

## Mental model

- **Every read waits and can fail**, so settle it with `?` or `else`
  ([language.md](language.md#a-call-that-can-fail)). `csv.write` neither
  waits nor fails, so it may stand in a `derive`.
- **A whole file is read in a worker** on a page, never on the page itself;
  a workbook by the `xlsx` battery (Mote's own wasm), CSV by the runtime.
- **What is read is data**: text, bytes, or a file picked with
  `{read: false}` ([data.md](data.md#files-not-read-yet)), which is then
  read in the worker and never comes to the page.
- **A typed read names a shape** as its second argument:
  `csv.records(data, Order)` gives `Order[]`. Its fields are matched to
  the header's names without regard to case, spaces or marks (`Unit
  price` is `unitPrice`), and each cell is turned into its field's type,
  or the read fails with where it is:
  `` csv: row 14, column "price": "12,5x" is not a number ``.
- **A field** is `string`, `number`, `bool`, `time` (a moment, in
  milliseconds, as `now()` gives), or `json` (the cell as it is), each with
  `?` if the cell may be empty. A list or a record there is `H281`; a name
  there that is no shape is `H280`.

## csv

```text
csv.read(data, {delimiter, skip, encoding}?)                   string[][]: every row, header and all
csv.records(data, {delimiter, header, skip, encoding}?)        json[]: records by the header's names, text values
csv.records(data, Order, {delimiter, header, decimal, thousands, dates}?)   Order[]
csv.open(file, Order?, {…}?)    a reader: r.header, r.next()? (the next rows, none at the end), r.stop()
csv.write(rows, {delimiter, lineEnd, bom, header, columns, decimal, formulas}?)   text, at once
```

**Reading** follows RFC 4180 and what the world writes besides:

- Quoted fields hold the delimiter, line breaks and doubled quotes
  (`"said ""hi"""`). A quote in the middle of a field that was not
  quoted is only a quote.
- Lines end in CRLF, LF or CR, mixed as they come. A line with nothing on
  it is not a row. Rows may have more or fewer cells than the header
  (ragged); a missing cell is empty.
- Bytes are decoded by their byte-order mark (UTF-8, UTF-16 either way),
  else as UTF-8, else (bytes that are not UTF-8) as Windows-1252, which is
  what Excel writes on Windows. `encoding: "iso-8859-2"` says another
  (any name `TextDecoder` knows).
- **The delimiter is guessed** from the first twenty lines among comma,
  semicolon, tab and bar (the one that comes as often on most lines);
  `delimiter: ";"` says it.
- `header: false`: there is no header row, and a shape's fields are the
  columns in order. `skip: 2` passes over the first two rows (a title
  above the header, say).
- **Numbers** are plain (`-12.5`, `1e3`); with `decimal: ","` and
  `thousands: "."` they are as much of Europe writes them (`1.234,5`). A
  number that has a comma in it and nothing said is refused with that
  advice.
- **Yes or no**: `true false yes no y n 1 0 on off x`, in any case; empty
  is no.
- **Dates** (`time`): `2026-11-12`, `2026-11-12T14:22`, `2026-11-12
  14:22:05`, with a zone (`Z`, `+01:00`) or read as UTC; `14:22` alone is
  that time of day. A date with slashes, dots or dashes needs its order
  said: `dates: "dmy"` (12.11.2026 is the 12th of November) or `"mdy"`;
  a two-digit year is 1950 to 2049. A whole number of nine digits or more is a moment's
  milliseconds, as `csv.write` writes a `time` (it has no way to know one:
  write `time.stamp(at, "UTC")` for a date a person reads).

**Writing** gives text; `fs.save(text, "orders.csv")?` hands it over.

- Rows are lists, or records: then the header is their keys (in the order
  `columns: ["item", "price"]` gives, else as first seen), unless
  `header: false`.
- A cell is quoted only when it must be: it has the delimiter, a quote, a
  line break, or space at either end.
- `delimiter: ";"`, `lineEnd: "\n"` (unsaid: `"\r\n"`, as RFC 4180 has
  it), `decimal: ","` for numbers, `bom: true` for Excel (which reads a
  file without one as its own code page, and garbles accents).
- **Formula injection**: a text that begins with `=`, `+`, `-`, `@`, a
  tab or a carriage return is written with a `'` before it, so that a
  spreadsheet shows it rather than running it (`=HYPERLINK(…)` in a
  customer's name). A text that is a plain number (`-5`) is left alone.
  `formulas: true` turns this off, for a file whose formulas are meant.

### A large file, a piece at a time

`csv.open` reads a picked file (or bytes, or text) about a megabyte at a
time: the page never holds the whole text, nor all its rows. `next()`
gives the rows that piece finished (typed, when a shape is named), and
`none` at the end.

```mote
// docs: whole
shape Order
  item: string
  price: number
  paid: bool

state said = ""

action total
  let f = fs.pick(".csv", {read: false})?
  if f == none return
  let r = csv.open(f, Order)?
  let sum = 0
  let n = 0
  while true
    let rows = r.next()?
    if rows == none break
    n += rows.length
    for o in rows
      sum += o.price
  said = `${n} orders, ${sum} in all (columns: ${r.header.join(", ")})`

button "Add up a CSV" press=total
text (failure(total) ?? said)
```

A million rows (41 MB) read so, typed, take a few seconds in headless
Chrome (`tests/sheets.real.mjs`). Without a shape, `next()` gives
`string[][]`. On the back end, `csv.open({path: "imports/orders.csv"})`
reads a file in the data folder the same way.

## xlsx

```text
xlsx.sheets(data)                   [{name, hidden, range}]: the sheets in order
xlsx.rows(data, {sheet, shown}?)    json[][]: one sheet's values
xlsx.records(data, Order?, {sheet, header, decimal, thousands, dates}?)
xlsx.read(data, {sheet}?)           everything: every sheet, every cell's kind, text and formula
xlsx.write(sheets, {formulas}?)     bytes: a .xlsx
```

`data` is a file's bytes, or a file picked unread. An OpenDocument
spreadsheet (`.ods`, what LibreOffice and Numbers export) is read by the
same calls ([below](#opendocument-spreadsheets)).

### Reading

- `sheet: "Totals"` or `sheet: 2` (from 0); unsaid, the first sheet that
  is not hidden (`xlsx.read`: all of them).
- **Rows** start at row 1 and column A: `rows[0][1]` is B1. Blank rows
  between are `[]`, blank cells `none`; blank cells and rows at the ends
  are left out.
- **Values**: a number; a text (shared strings, inline strings, rich text
  flattened to its characters); `true` or `false`; an error as its text
  (`"#DIV/0!"`); a **date as a stamp**, `"2026-11-12"` or
  `"2026-11-12T14:22:05"` (`time.read` takes it), or `"14:22:05"` for a
  time of day. Into a `time` field it is the moment (read as UTC).
- **Dates are numbers with a date's format**, counted in days. Both of
  Excel's systems are read: the 1900 system, with its 29th of February
  1900 (a day that never was, which Lotus 1-2-3 counted and Excel kept: it
  reads as `"1900-02-29"`, and as a `time`, the 1st of March), and the
  1904 system of old Mac workbooks. A plain number read into a `time`
  field is taken for such a day count.
- `shown: true` gives each cell as the text Excel shows: its number format
  applied (`1,234.50`, `12.5%`, `$1,234.50`, `3/15/2023`, `6:00 PM`).
- **Formulas** are not worked out: a cell gives the value Excel kept with
  it. `xlsx.read` also gives its text (`SUM(B2:B9)`, without `=`); a
  shared formula is given as it reads in its own cell.
- `xlsx.records`: the header is the first row with anything in it, or the
  row `header: 3` says (as Excel numbers it); `header: false` is none. A
  failure says the row as Excel numbers it and the column's letter:
  `` xlsx: row 7, column C ("price"): "n/a" is not a number ``.

`xlsx.read` gives `{sheets, date1904, ignored}`. Each sheet is
`{name, hidden, range, merged, hiddenRows, hiddenCols, rows}`: `range` is
where its cells are (`"A1:D20"`), `merged` its merged ranges
(`["A1:C1"]`), `hiddenRows` and `hiddenCols` numbered from 1, and each
cell `{kind, value, text, format, formula?, link?, serial?}`: `kind` is
`number`, `text`, `bool`, `date`, `error` or `blank`; `text` what Excel
shows; `format` its number format's code (`"0.00"`, `"m/d/yyyy"`); `link`
its hyperlink; `serial` a date's day count.

**Number formats** handled: General (Excel's eleven characters, then a
power of ten); `0`, `#`, `?`, the point, thousands commas and commas that
divide by a thousand; `%`; `E+`; fractions (`# ?/?`, `?/8`); up to four
sections (positive; negative; zero; text) and conditions (`[>=1000]`);
colours (dropped: text has none); currency (`[$€-407]`); quoted and `\`
literals; `_` and `*`; dates and times (`yyyy mmm d dddd h mm ss`,
`AM/PM`, `[h]:mm` lengths of time, `.000` of a second); `@`. Built-in
formats are as an English (US) Excel shows them (14 is `m/d/yyyy`). Not
handled (shown as General or as written): other calendars (`B2`), the
East Asian built-in formats (read as `m/d/yyyy` dates), `[DBNum]` and
other locale codes beyond a currency's symbol.

**What is not read**, said plainly:

| | |
|---|---|
| `.xls` (Excel 97 to 2003, a binary format) | Refused: `this is an .xls file, Excel's format before 2007, which is not read: open it in Excel and save it as an Excel Workbook (.xlsx)`. |
| A workbook with a password | Refused: it is encrypted (`save a copy without one … and read that`). |
| `.xlsb` | Refused, with a sentence that says to save it as `.xlsx`. |
| `.xlsm` | Read as data; its macros are dropped. |
| Charts, chart sheets, pivot tables, images, comments, slicers, links to other workbooks, data connections | Not read. `ignored` names those the file has (`["macros", "charts"]`), for the page to say. A pivot table's cells are read as the cells they are. |
| Styles | Not given, bar each cell's number format. |

**Large workbooks.** The package's directory is read once and only the
parts wanted are inflated: other sheets, and pictures, never are. A sheet
is read in one pass over its XML, row by row, with nothing built but what
is given back. Its XML is inflated whole first (about 30 bytes a cell),
so a sheet of a few million cells is fine and one of a hundred million is
not; the whole file, and what is given back, are also in memory.

### OpenDocument spreadsheets

`xlsx.sheets`, `rows`, `records` and `read` read an `.ods` too: its
`content.xml`, in one pass. Each cell's value is as the file keeps it (a
number, a text, `true`/`false`, a date or a time of day as a stamp), and
`shown` is the text the file keeps beside it, as LibreOffice showed it.
Formulas are given as Excel writes them (`of:=[.B2]*2` is `B2*2`),
merges as ranges, and repeated rows and cells (a blank row said to repeat
a million times) are written out only up to the last with something in it.
Not read: which sheets, rows and columns are hidden, and formats' codes
(`format` is `""`). `.ods` is read, not written.

### Writing

```mote
// docs: whole
shape Line
  item: string
  qty: number
  price: number
  due: time

state lines: Line[] = [{item: "Oak door", qty: 2, price: 412.5, due: 1794441600000}, {item: "Ash shelf", qty: 5, price: 38, due: 1794528000000}]

action save
  let book = xlsx.write([
    {name: "Quote", rows: lines, columns: [{key: "item", title: "Item", width: 24}, {key: "qty", title: "Qty", format: "integer"}, {key: "price", title: "Price", format: "currency"}, {key: "due", title: "Due", format: "date"}], filter: true},
    {name: "Total", header: false, rows: [["Total", {formula: "SUMPRODUCT(Quote!B2:B3,Quote!C2:C3)", format: "currency", bold: true}], [{value: "Our site", link: "https://example.com"}, {value: "Thank you", fill: "#fff3c4", align: "center", border: true}]], merge: []}
  ])?
  fs.save(book, "quote.xlsx")?

button "Save the quote" press=save
text (failure(save) ?? "")
```

A sheet is `{name, rows, columns?, header?, freeze?, filter?, merge?}`:

- **`rows`**: records (each key a column, in the order `columns` gives or
  as first seen; a header row of their names, or the columns' `title`s),
  or lists of cells.
- **A cell** is a number, a text, `true`/`false`, `none` (blank), or a
  record: `{value, format, bold, …}`, `{date: at}` (a moment, written as
  a real date), `{formula: "SUM(B2:B9)"}` (without `=`; worked out when
  the file is opened), `{value: "Site", link: "https://…"}` (or
  `"#'Other sheet'!A1"`), `{error: "#N/A"}`.
- **Types are kept**: a number is a number, a date a date with a format,
  a bool a bool. A column whose `format` is `"date"`, `"datetime"` or
  `"time"` takes its numbers for moments.
- **`columns`**: `[{key, title, width, hidden, format, bold, …}]`, in
  order. `width` is in characters; unsaid, a column is **fitted to what
  is in it** (6 to 60).
- **`header`** (unsaid: true for records, false for lists) makes the
  first row bold and frozen. `freeze: 2` freezes that many rows, `freeze:
  [1, 1]` a row and a column, `freeze: 0` none.
- `filter: true` puts an autofilter on the header and what is under it;
  `filter: "A1:D40"` on that range. `merge: ["A1:C1"]` merges cells.
- **Formats** by name: `"general"`, `"integer"` (`#,##0`), `"decimal"`
  (`#,##0.00`), `"currency"` (`"$"#,##0.00`), `"percent"` (`0%`), `"date"`
  (`yyyy-mm-dd`), `"time"`, `"datetime"`, `"text"` (`@`); or any code
  (`"0.0%"`, `"€#,##0.00"`, `"d mmm yyyy"`).
- **Styles**, kept small: `bold`, `italic`, `underline`, `size`, `font`,
  `color` and `fill` (`"#rrggbb"`), `align` (`left`, `center`, `right`),
  `valign` (`top`, `middle`, `bottom`), `wrap`, `border` (`true`, or
  `"thin"`, `"medium"`, `"thick"`, `"dashed"`, `"dotted"`, `"double"`). On
  a cell, or on a column for every cell in it.
- **Sheet names are made legal**: none of `[ ] : * ? / \` (each becomes
  `-`), no `'` at either end, 31 characters at most, not `History`, and
  unlike the others (`Orders (2)`).
- **The same care with formulas as CSV**: a text that begins with `=`,
  `+`, `-` or `@` is written as text and marked so (`quotePrefix`), so
  Excel shows it and keeps it text when it is edited. `{formulas: true}`
  makes a text that begins with `=` a formula.
- Refused, as Excel would repair them: merges that overlap, a text over
  32,767 characters, more than 1,048,576 rows or 16,384 columns.

What is written is the fewest parts a workbook needs (content types,
relationships, the workbook, a sheet each, styles, shared strings,
`docProps/app.xml`), zipped by Mote's own `zip`. Each part is checked to
be well-formed, and the package to name every part's type and to reach
every part from its relationships, in `compiler/src/tests_xlsx.rs` and
by `xmllint` and Python's `zipfile` against what `tests/sheets` writes.
Read back by this battery and by `unzip`. **Not yet opened in Excel,
Numbers, LibreOffice or Google Sheets by a test.**

Reading a workbook and writing it again keeps its values, not its look,
its charts or its other parts.

## On the back end

The same calls in a `server fn`, where the same code and wasm run in
place: an export built where the data is, an upload read where it lands.

```mote
// docs: whole
model Sale
  item: string
  amount: number
  read, add anyone

shape SaleRow
  item: string
  amount: number

server fn exportSales(): bytes
  let sales = Sale.find({}, {order: "item"})?
  return xlsx.write([{name: "Sales", rows: sales.map(s => ({item: s.item, amount: s.amount})), columns: [{key: "item", title: "Item"}, {key: "amount", title: "Amount", format: "currency"}]}])?

server fn importSales(file: bytes): number
  let rows = file[0] == 80 ? xlsx.records(file, SaleRow)? : csv.records(file, SaleRow)?
  for r in rows
    Sale.add({item: r.item, amount: r.amount})?
  return rows.length

state said = ""

action upload
  let f = fs.pick(".csv,.xlsx")?
  if f == none return
  said = `${importSales(f.data)?} rows added`

action download
  fs.save(exportSales()?, "sales.xlsx")?

row gap=8
  button "Import" press=upload
  button "Export" press=download
text (failure(upload) ?? said)
```

(`80` is `P`: a workbook is a zip, and a zip begins `PK`.)

## Pitfalls

- **A typed read is only as good as the header.** Name the shape's fields
  as the columns are named (case and spaces do not matter), or read with
  `header: false` and fields in the columns' order.
- **A date in a CSV with slashes needs `dates:`**: `03/04/2026` is March or
  April only by what the file's maker meant.
- **Formulas are not worked out** when a workbook is read: the value is the
  one Excel saved. A file written by a program that saves no values gives
  `none` for its formula cells.
- **A whole file is in memory** for `csv.read`, `csv.records` and every
  `xlsx` call; for CSV too large for that, `csv.open`.

## In the source

| What | Where |
|---|---|
| Signatures and messages (`H280`, `H281`) | `compiler/src/types/sheets.rs` |
| What each call compiles to | `compiler/src/emit/sheets.rs` |
| CSV, typed rows, the driver of the battery | `runtime/shared/sheets.mote`: part `SH` |
| Workbooks: the package, XML, dates and formats, reading, writing | `batteries/xlsx/` (`pkg.rs`, `xml.rs`, `numfmt.rs`, `read.rs`, `write.rs`) |
| Tests | `compiler/src/tests_xlsx.rs` (workbooks made by hand and zipped by Mote's own zip); `tests/sheets` and `tests/expect/real_sheets.txt` (in Chrome and Bun) |
