// A workbook writer: the one thing the export needs, in ~100 lines and no dependency.
//
// An .xlsx file is a ZIP of a few XML parts. This writes the five parts a spreadsheet application
// needs (plus a styles part for the bold header row) as an uncompressed ZIP, which every reader
// accepts. Choosing it over a library is a supply-chain decision (spec §12): the template's export
// is a table of strings and numbers, and a general workbook library is thousands of lines of code
// in a customer's dependency tree for that.
//
// Two properties are deliberate and tested. Every string is an inline string, so a value that
// begins `=`, `+`, `-` or `@` is text a spreadsheet displays and never a formula it evaluates (a
// document's text is attacker-controlled input). And the output is a pure function of its input
// -- fixed timestamps, fixed order -- so the same lines are the same bytes.
export type Cell = string | number
const encoder = new TextEncoder()
/** CRC-32 (IEEE), as ZIP requires. */
const CRC_TABLE = ((): Uint32Array => {
const table = new Uint32Array(256)
for (let n = 0; n < 256; n += 1) {
let c = n
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
table[n] = c >>> 0
}
return table
})()
function crc32(bytes: Uint8Array): number {
let crc = 0xffffffff
for (const byte of bytes) crc = (CRC_TABLE[(crc ^ byte) & 0xff] as number) ^ (crc >>> 8)
return (crc ^ 0xffffffff) >>> 0
}
/** Characters XML 1.0 cannot carry at all, removed rather than escaped. */
// biome-ignore lint/suspicious/noControlCharactersInRegex: matching control characters is the point.
const NOT_XML = /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/gu
const escapeXml = (text: string): string =>
text.replace(NOT_XML, "").replace(/&/g, "&").replace(//g, ">").replace(/"/g, """)
/** `0 -> A`, `25 -> Z`, `26 -> AA`. */
function columnName(index: number): string {
let name = ""
for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26)) name = String.fromCharCode(65 + ((n - 1) % 26)) + name
return name
}
const XML = '\n'
function sheetXml(rows: readonly (readonly Cell[])[]): string {
const body = rows
.map((row, r) => {
const cells = row
.map((cell, c) => {
const ref = `${columnName(c)}${r + 1}`
if (typeof cell === "number") {
if (!Number.isFinite(cell)) throw new Error(`a workbook cell must be a finite number: ${ref}`)
return `${cell}`
}
// The first row is the header and takes the bold style.
return `${escapeXml(cell)}`
})
.join("")
return `${cells}
`
})
.join("")
return `${XML}${body}`
}
const STYLES =
`${XML}` +
'' +
'' +
'' +
'' +
'' +
''
const CONTENT_TYPES =
`${XML}` +
'' +
'' +
'' +
'' +
''
const ROOT_RELS =
`${XML}` +
''
const WORKBOOK_RELS =
`${XML}` +
'' +
''
const workbookXml = (sheetName: string): string =>
`${XML}` +
``
/** What Excel refuses in a sheet name: empty, over 31 characters, or one of `[]:*?/\`. */
const BAD_SHEET_NAME = /[[\]:*?/\\]/u
interface Part {
readonly name: string
readonly data: Uint8Array
}
/** DOS date 1980-01-01, time 00:00: a fixed stamp keeps the output reproducible. */
const DOS_TIME = 0
const DOS_DATE = (0 << 9) | (1 << 5) | 1
function zip(parts: readonly Part[]): Uint8Array {
const chunks: Uint8Array[] = []
const central: Uint8Array[] = []
let offset = 0
for (const part of parts) {
const name = encoder.encode(part.name)
const crc = crc32(part.data)
const local = new Uint8Array(30 + name.length)
const lv = new DataView(local.buffer)
lv.setUint32(0, 0x04034b50, true)
lv.setUint16(4, 20, true) // version needed
lv.setUint16(6, 0x0800, true) // UTF-8 names
lv.setUint16(8, 0, true) // stored
lv.setUint16(10, DOS_TIME, true)
lv.setUint16(12, DOS_DATE, true)
lv.setUint32(14, crc, true)
lv.setUint32(18, part.data.length, true)
lv.setUint32(22, part.data.length, true)
lv.setUint16(26, name.length, true)
local.set(name, 30)
chunks.push(local, part.data)
const entry = new Uint8Array(46 + name.length)
const cv = new DataView(entry.buffer)
cv.setUint32(0, 0x02014b50, true)
cv.setUint16(4, 20, true) // version made by
cv.setUint16(6, 20, true)
cv.setUint16(8, 0x0800, true)
cv.setUint16(10, 0, true)
cv.setUint16(12, DOS_TIME, true)
cv.setUint16(14, DOS_DATE, true)
cv.setUint32(16, crc, true)
cv.setUint32(20, part.data.length, true)
cv.setUint32(24, part.data.length, true)
cv.setUint16(28, name.length, true)
cv.setUint32(42, offset, true)
entry.set(name, 46)
central.push(entry)
offset += local.length + part.data.length
}
const directorySize = central.reduce((sum, entry) => sum + entry.length, 0)
const end = new Uint8Array(22)
const ev = new DataView(end.buffer)
ev.setUint32(0, 0x06054b50, true)
ev.setUint16(8, parts.length, true)
ev.setUint16(10, parts.length, true)
ev.setUint32(12, directorySize, true)
ev.setUint32(16, offset, true)
const all = [...chunks, ...central, end]
const out = new Uint8Array(all.reduce((sum, chunk) => sum + chunk.length, 0))
let at = 0
for (const chunk of all) {
out.set(chunk, at)
at += chunk.length
}
return out
}
/** One sheet of rows; the first row is the header. */
export function buildWorkbook(sheetName: string, rows: readonly (readonly Cell[])[]): Uint8Array {
if (sheetName.length === 0 || sheetName.length > 31 || BAD_SHEET_NAME.test(sheetName)) {
throw new Error("a workbook sheet name is 1 to 31 characters without [ ] : * ? / \\")
}
const text = (name: string, xml: string): Part => ({ name, data: encoder.encode(xml) })
return zip([
text("[Content_Types].xml", CONTENT_TYPES),
text("_rels/.rels", ROOT_RELS),
text("xl/workbook.xml", workbookXml(sheetName)),
text("xl/_rels/workbook.xml.rels", WORKBOOK_RELS),
text("xl/styles.xml", STYLES),
text("xl/worksheets/sheet1.xml", sheetXml(rows)),
])
}