/** * Import a `.xlsx` workbook into a `@tanstack/spreadsheet-core` `Workbook`. * * Tier 1: cell values + formulas. Because the engine recomputes on import, the * cached `` values only matter as a *fallback* — a formula that uses a * function we don't implement (or otherwise won't parse) is imported as its * cached value instead of erroring, so the sheet still reads correctly and * everything we do support stays live. Number-format codes are carried through * as display metadata via `workbook.setFormat`. * * Not imported: styles/fonts/fills, column widths, conditional formatting, * charts, images, data validation, comments, pivots, structured/table refs, * array/dynamic formulas. */ import { XMLParser } from 'fast-xml-parser' import { strFromU8, unzipSync } from 'fflate' import { ParseError, createWorkbook, isDateFormat, makeRect, parse, parseA1, translateFormula, } from '@tanstack/spreadsheet-core' import { BUILTIN_NUMFMTS } from './numfmt' import { DROPPED_FEATURES } from './drops' import type { FunctionRegistry, Issue, Node, Patch, Rect, Ref, Workbook, } from '@tanstack/spreadsheet-core' export interface ImportResult { workbook: Workbook sheetNames: Array /** * Every cell-by-cell and workbook-level problem found during import — enough * to highlight degraded cells in red. Covers unsupported formulas, unknown * number formats, and surviving dropped features. */ issues: Array /** Aggregates over {@link issues}: totals and a count per reason kind. */ summary: { /** Populated cells imported. */ cells: number /** `issues.length`. */ issues: number /** Count of issues by {@link Issue.kind}. */ byKind: Record } } // --------------------------------------------------------------------------- // XML helpers // --------------------------------------------------------------------------- const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_', textNodeName: '#text', parseAttributeValue: false, parseTagValue: false, trimValues: false, }) function toArray(x: T | Array | undefined): Array { return x === undefined ? [] : Array.isArray(x) ? x : [x] } function textOf(x: unknown): string { if (x === undefined || x === null) return '' if (typeof x === 'string') return x if (typeof x === 'object' && '#text' in x) { return String((x as Record)['#text'] ?? '') } return String(x) } // --------------------------------------------------------------------------- // Part readers // --------------------------------------------------------------------------- function readSharedStrings(files: Record): Array { const raw = files['xl/sharedStrings.xml'] if (!raw) return [] const doc = parser.parse(strFromU8(raw)) return toArray(doc?.sst?.si).map((si: any) => { if (si.t !== undefined) return textOf(si.t) // rich-text runs return toArray(si.r) .map((run: any) => textOf(run.t)) .join('') }) } interface StyleInfo { /** styleIndex -> number-format code (or undefined for General). */ codes: Array /** styleIndex -> numFmtId, for style indices whose id we don't recognise. */ unknown: Map } function readStyles(files: Record): StyleInfo { const raw = files['xl/styles.xml'] if (!raw) return { codes: [], unknown: new Map() } const doc = parser.parse(strFromU8(raw)) const custom: Record = {} for (const nf of toArray(doc?.styleSheet?.numFmts?.numFmt)) { custom[Number(nf['@_numFmtId'])] = String(nf['@_formatCode']) } const unknown = new Map() const codes = toArray(doc?.styleSheet?.cellXfs?.xf).map( (xf: any, idx: number) => { const id = Number(xf['@_numFmtId'] ?? 0) const code = custom[id] ?? BUILTIN_NUMFMTS[id] // id 0 is General (no format); only flag a *referenced-but-unknown* id. if (code === undefined && id !== 0) unknown.set(idx, id) return code && code !== 'General' ? code : undefined }, ) return { codes, unknown } } /** Workbook-level metadata: the 1904 date system flag and defined names. */ function readWorkbookMeta(files: Record): { date1904: boolean definedNames: Array<{ name: string definition: string localSheetId?: number }> } { const wb = parser.parse(strFromU8(files['xl/workbook.xml']!)) const pr = wb?.workbook?.workbookPr const date1904 = pr?.['@_date1904'] === '1' || pr?.['@_date1904'] === 'true' const definedNames = toArray(wb?.workbook?.definedNames?.definedName).map( (d: any) => ({ name: String(d['@_name']), definition: textOf(d), localSheetId: d['@_localSheetId'] !== undefined ? Number(d['@_localSheetId']) : undefined, }), ) return { date1904, definedNames } } /** Merge rectangles declared on a worksheet document, as A1 range strings. */ function readMergeRefs(doc: any): Array { return toArray(doc?.worksheet?.mergeCells?.mergeCell).map((m: any) => String(m['@_ref']), ) } function readSheetList( files: Record, ): Array<{ name: string; path: string }> { const wb = parser.parse(strFromU8(files['xl/workbook.xml']!)) const rels = files['xl/_rels/workbook.xml.rels'] const relMap: Record = {} if (rels) { for (const rel of toArray( parser.parse(strFromU8(rels))?.Relationships?.Relationship, )) { relMap[String(rel['@_Id'])] = String(rel['@_Target']) } } return toArray(wb?.workbook?.sheets?.sheet).map((s: any, i: number) => { const rid = s['@_r:id'] ?? s['@_ns0:id'] const target = relMap[rid] let path: string if (target) { path = target.startsWith('/') ? target.slice(1) : 'xl/' + target } else { path = `xl/worksheets/sheet${i + 1}.xml` // fallback by convention } return { name: String(s['@_name'] ?? `Sheet${i + 1}`), path } }) } // --------------------------------------------------------------------------- // Formula support detection (for the cached-value fallback) // --------------------------------------------------------------------------- function collectCallNames(node: Node, out: Set): void { switch (node.type) { case 'call': out.add(node.name) node.args.forEach((a) => collectCallNames(a, out)) break case 'unary': collectCallNames(node.operand, out) break case 'binary': collectCallNames(node.left, out) collectCallNames(node.right, out) break default: break } } function isFormulaSupported( input: string, registry: FunctionRegistry, ): boolean { try { const ast = parse(input) const names = new Set() collectCallNames(ast, names) for (const n of names) if (!registry.has(n)) return false return true } catch (e) { if (e instanceof ParseError) return false throw e } } // --------------------------------------------------------------------------- // Cell -> input string // --------------------------------------------------------------------------- /** A literal input string derived from a cell's type + cached value. */ function literalInput( t: string | undefined, v: string, shared: Array, inlineStr: string | undefined, ): string { switch (t) { case 's': return "'" + (shared[Number(v)] ?? '') // shared string, force text case 'str': return "'" + v // formula string result, as text case 'inlineStr': return "'" + (inlineStr ?? '') case 'b': return v === '1' ? 'TRUE' : 'FALSE' case 'e': return '=' + v // error literal (e.g. =#DIV/0!) default: return v // number } } // --------------------------------------------------------------------------- // Import // --------------------------------------------------------------------------- export function importXlsx( data: Uint8Array | ArrayBuffer, opts: { workbook?: Workbook } = {}, ): ImportResult { const bytes = data instanceof Uint8Array ? data : new Uint8Array(data) const files = unzipSync(bytes) const shared = readSharedStrings(files) const styles = readStyles(files) const sheets = readSheetList(files) const meta = readWorkbookMeta(files) const workbook = opts.workbook ?? createWorkbook() const registry = workbook.functions const issues: Array = [] // Atomic against sheet-name collisions: validate every name BEFORE adding any // sheet, so a bad file never leaves a half-imported workbook. const seen = new Set() for (const { name } of sheets) { if (seen.has(name) || workbook.getSheet(name)) { throw new Error( `xlsx import aborted: duplicate or colliding sheet name '${name}'`, ) } seen.add(name) } for (const { name } of sheets) workbook.addSheet(name) const patches: Array = [] const formatOps: Array<{ ref: Ref; code: string }> = [] const mergeOps: Array<{ sheet: string; rect: Rect }> = [] let cells = 0 for (const { name, path } of sheets) { const raw = files[path] if (!raw) continue const doc = parser.parse(strFromU8(raw)) const docText = strFromU8(raw) const sharedFormulas = new Map< string, { formula: string; row: number; col: number } >() // Merges travel (Phase 2 made merges core state). for (const mref of readMergeRefs(doc)) { const rect = parseA1Range(mref) if (rect) mergeOps.push({ sheet: name, rect }) } // Surviving dropped features that are present → a reported issue, not silence. for (const d of DROPPED_FEATURES) { if (d.element && docText.includes('<' + d.element)) { issues.push({ kind: 'dropped-feature', message: `'${d.label}' on sheet '${name}' were dropped (not supported)`, }) } } for (const row of toArray(doc?.worksheet?.sheetData?.row)) { for (const c of toArray(row.c)) { const a1 = c['@_r'] if (!a1) continue const addr = parseA1(String(a1)) if (!addr) continue const ref: Ref = { sheet: name, row: addr.row, col: addr.col } // number format (display metadata) const styleIdx = c['@_s'] !== undefined ? Number(c['@_s']) : -1 const code = styleIdx >= 0 ? styles.codes[styleIdx] : undefined if (code) formatOps.push({ ref, code }) if (styleIdx >= 0 && styles.unknown.has(styleIdx)) { issues.push({ kind: 'unknown-number-format', message: `unknown number-format id ${styles.unknown.get(styleIdx)} on ${a1}`, ref, }) } const t = c['@_t'] as string | undefined const v = c.v !== undefined ? textOf(c.v) : '' const inlineStr = c.is ? textOf(c.is.t) : undefined const isArrayFormula = typeof c.f === 'object' && c.f['@_t'] === 'array' let input: string | undefined if (c.f !== undefined) { // formula cell (possibly shared / array) const f = c.f const fText = textOf(f) const fType = typeof f === 'object' ? f['@_t'] : undefined const si = typeof f === 'object' ? f['@_si'] : undefined let formula = fText if (fType === 'shared') { if (f['@_ref'] !== undefined && fText) { sharedFormulas.set(String(si), { formula: fText, row: addr.row, col: addr.col, }) } else if (si !== undefined && sharedFormulas.has(String(si))) { const master = sharedFormulas.get(String(si))! formula = translateFormula( '=' + master.formula, addr.row - master.row, addr.col - master.col, ).slice(1) // drop leading '=' } } if (isArrayFormula) { // Array formulas are a documented drop — keep the cached value. issues.push({ kind: 'dropped-feature', message: `array formula on ${a1} imported as its cached value`, ref, original: '=' + formula, }) input = v !== '' || t ? literalInput(t, v, shared, inlineStr) : undefined } else if (formula) { const candidate = '=' + formula if (isFormulaSupported(candidate, registry)) { input = candidate } else { // fallback: import the cached value as a literal; report it issues.push({ kind: 'unsupported-formula', message: `formula on ${a1} not supported; kept its cached value`, ref, original: candidate, }) input = v !== '' || t ? literalInput(t, v, shared, inlineStr) : candidate } } else if (v !== '' || t) { input = literalInput(t, v, shared, inlineStr) } } else { // literal cell if (v !== '' || inlineStr !== undefined) { input = literalInput(t, v, shared, inlineStr) } } // 1904 date system: a date-formatted serial is 1462 days off the 1900 // system this engine uses — shift it so dates land on the right day. if ( meta.date1904 && input !== undefined && code && isDateFormat(code) && /^-?\d+(\.\d+)?$/.test(input) ) { input = String(Number(input) + 1462) } if (input !== undefined && input !== '') { patches.push(...workbook.setInput(ref, input)) cells++ } } } } workbook.applyPatches(patches) for (const { ref, code } of formatOps) workbook.setFormat(ref, code) for (const { sheet, rect } of mergeOps) workbook.mergeCells(sheet, rect) // Defined names travel. A localSheetId scopes the name to that sheet. for (const dn of meta.definedNames) { const scope = dn.localSheetId !== undefined ? sheets[dn.localSheetId]?.name : undefined try { workbook.defineName(dn.name, dn.definition, scope ? { scope } : {}) } catch (e) { issues.push({ kind: 'dropped-feature', message: `defined name '${dn.name}' could not be imported: ${ e instanceof Error ? e.message : String(e) }`, original: dn.definition, }) } } const byKind: Record = {} for (const i of issues) byKind[i.kind] = (byKind[i.kind] ?? 0) + 1 return { workbook, sheetNames: sheets.map((s) => s.name), issues, summary: { cells, issues: issues.length, byKind }, } } /** Parse an A1 range like `A1:C3` (or a single cell) into a {@link Rect}. */ function parseA1Range(s: string): Rect | null { const [a, b] = s.split(':') const p0 = a ? parseA1(a) : null if (!p0) return null const p1 = b ? parseA1(b) : p0 if (!p1) return null return makeRect(p0.row, p0.col, p1.row, p1.col) }