diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b1fe20d..ee1ce46 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -245,6 +245,9 @@ importers: nanoid: specifier: ^6.0.1 version: 6.0.1 + numfmt: + specifier: ^4.1.1 + version: 4.1.1 p5: specifier: ^2.3.3 version: 2.3.3 @@ -3168,6 +3171,9 @@ packages: resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} engines: {node: '>=0.10.0'} + numfmt@4.1.1: + resolution: {integrity: sha512-12MJtolvN20WANpEm1LjEZrUgnjnBxg9Rp5FpXZZO06NInd7zc5cu8DOjVkrYfeWswNBOmDeD0MuJEYkVf5kzQ==} + object-assign@4.1.1: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} @@ -6951,6 +6957,8 @@ snapshots: normalize-path@3.0.0: {} + numfmt@4.1.1: {} + object-assign@4.1.1: {} obug@2.2.1: {} diff --git a/ui-packages/web/package.json b/ui-packages/web/package.json index af6f4e8..8b37702 100644 --- a/ui-packages/web/package.json +++ b/ui-packages/web/package.json @@ -37,6 +37,7 @@ "mermaid": "^12.0.0", "minisearch": "^7.2.0", "nanoid": "^6.0.1", + "numfmt": "^4.1.1", "p5": "^2.3.3", "pdfjs-dist": "^6.3.289", "react": "^19.3.0", diff --git a/ui-packages/web/src/features/assistant/create-reader-agent.test.ts b/ui-packages/web/src/features/assistant/create-reader-agent.test.ts index 0abb6e3..c6980b8 100644 --- a/ui-packages/web/src/features/assistant/create-reader-agent.test.ts +++ b/ui-packages/web/src/features/assistant/create-reader-agent.test.ts @@ -54,6 +54,7 @@ vi.mock('mammoth', () => ({ const xlsx = vi.hoisted(() => ({ read: vi.fn() })) vi.mock('read-excel-file/browser', () => ({ default: xlsx.read })) +vi.mock('../../formats/xlsx-package', () => ({ readSheetDetails: async () => new Map() })) const config = await createModelRuntime(modelConfig) const event = (delta: unknown, finish: string | null = null, tokens = 0) => diff --git a/ui-packages/web/src/features/assistant/xlsx/SKILL.md b/ui-packages/web/src/features/assistant/xlsx/SKILL.md index 4d9569a..de43dcf 100644 --- a/ui-packages/web/src/features/assistant/xlsx/SKILL.md +++ b/ui-packages/web/src/features/assistant/xlsx/SKILL.md @@ -3,5 +3,6 @@ - sheet_info discovers sheet names, sizes and A1 extents. sheet_read reads a known region directly; search locates values without scanning row by row. A sheet name such as "2" takes precedence over its numeric position. - A row has a separate row number and cells ordered by the returned columns. The row number is not column A. Cite sheet and cell coordinates. read/search instead expose workbook text as lines, including sheet headings; their line numbers are not spreadsheet row numbers. - When sheet_read returns nextRow, continue with a range starting there. read/search use opaque next cursors instead. -- Empty cells, empty sheets and non-leading cells of a merged block can be genuinely empty. Do not substitute zero. Headers are content, not designated metadata. -- Formulas expose saved values, not recalculated results; without a saved value they read as empty. Distinguish your calculations from stored values. These tools cannot modify XLSX files; CSV is a writable text alternative when requested. +- Empty cells and empty sheets can be genuinely empty. Do not substitute zero. Headers are content, not designated metadata. +- A merged block keeps its value in its top-left cell and the rest of the block empty; the value belongs to the whole block. sheet_info, sheet_read and each sheet heading in read list the merged blocks. +- Numbers read as the sheet displays them, such as 15.3% or ¥12,345.60. An error cell reads as its error, such as #DIV/0!. Formulas expose saved values, not recalculated results; one without a saved value reads as its formula, such as =SUM(A2:C2). Distinguish your calculations from stored values. These tools cannot modify XLSX files; CSV is a writable text alternative when requested. diff --git a/ui-packages/web/src/features/assistant/xlsx/tools.test.ts b/ui-packages/web/src/features/assistant/xlsx/tools.test.ts index eb4cc00..2fc9b76 100644 --- a/ui-packages/web/src/features/assistant/xlsx/tools.test.ts +++ b/ui-packages/web/src/features/assistant/xlsx/tools.test.ts @@ -22,7 +22,11 @@ const workbook: Worksheet[] = [ ['询单', 3], ], }, - { name: '汇总', rows: [['合计', 3]] }, + { + name: '汇总', + rows: [['合计', 3]], + merges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }], + }, ] describe('sheet_info', () => { @@ -31,7 +35,7 @@ describe('sheet_info', () => { fileId: 'f', sheets: [ { number: 1, name: '数据', rows: 2, columns: 2, extent: 'A1:B2' }, - { number: 2, name: '汇总', rows: 1, columns: 2, extent: 'A1:B1' }, + { number: 2, name: '汇总', rows: 1, columns: 2, extent: 'A1:B1', merged: ['A1:B1'] }, ], }) }) @@ -53,6 +57,11 @@ describe('sheet_read', () => { const byNumber = await call(workbook, 'sheet_read', { fileId: 'f', sheet: '2' }) expect(byName).toEqual(byNumber) expect(byName.sheet).toBe('汇总') + // A block the rows touch is named, so a value is read as covering all of it. + expect(byName.merged).toEqual(['A1:B1']) + expect( + await call(workbook, 'sheet_read', { fileId: 'f', sheet: '汇总', range: 'C1' }), + ).not.toHaveProperty('merged') expect((await call(workbook, 'sheet_read', { fileId: 'f' })).sheet).toBe('数据') }) diff --git a/ui-packages/web/src/features/assistant/xlsx/tools.ts b/ui-packages/web/src/features/assistant/xlsx/tools.ts index 27b4ba4..b67a47d 100644 --- a/ui-packages/web/src/features/assistant/xlsx/tools.ts +++ b/ui-packages/web/src/features/assistant/xlsx/tools.ts @@ -4,6 +4,7 @@ import { type CellRange, columnCount, parseRange, + rangeLabel, selectCells, sheetExtent, type Worksheet, @@ -35,6 +36,12 @@ const pickSheet = (sheets: readonly Worksheet[], wanted?: string) => { return { number, sheet } } +const overlaps = (a: CellRange, b: CellRange) => + a.startRow <= b.endRow && + b.startRow <= a.endRow && + a.startColumn <= b.endColumn && + b.startColumn <= a.endColumn + export const createXlsxTools = (xlsx: XlsxRuntime) => [ bind( 'sheet_info', @@ -50,6 +57,7 @@ export const createXlsxTools = (xlsx: XlsxRuntime) => [ rows: sheet.rows.length, columns: columnCount(sheet.rows), extent: sheetExtent(sheet), + ...(sheet.merges?.length ? { merged: sheet.merges.map(rangeLabel) } : {}), })), } }, @@ -77,6 +85,8 @@ export const createXlsxTools = (xlsx: XlsxRuntime) => [ }) const build = (count: number) => { const nextRow = selection.startRow + count + const block = { ...range, startRow: selection.startRow, endRow: nextRow - 1 } + const merged = sheet.merges?.filter(merge => overlaps(merge, block)).map(rangeLabel) ?? [] return { fileId, sheet: sheet.name, @@ -88,6 +98,7 @@ export const createXlsxTools = (xlsx: XlsxRuntime) => [ row: selection.startRow + index, cells, })), + ...(merged.length ? { merged } : {}), ...(nextRow <= lastRow ? { nextRow } : {}), } } diff --git a/ui-packages/web/src/features/reader/xlsx-reader/index.tsx b/ui-packages/web/src/features/reader/xlsx-reader/index.tsx index 410985e..c1baa04 100644 --- a/ui-packages/web/src/features/reader/xlsx-reader/index.tsx +++ b/ui-packages/web/src/features/reader/xlsx-reader/index.tsx @@ -84,7 +84,7 @@ export const XlsxReader = ({ const sheets = state.status === 'ready' ? state.sheets : [] // A saved sheet the workbook no longer has falls back to the first. const sheetIndex = sheets[selected] ? selected : 0 - const rows = sheets[sheetIndex]?.rows ?? [] + const sheet = sheets[sheetIndex] if (state.status === 'loading') return
Opening {document.path}…
@@ -120,7 +120,8 @@ export const XlsxReader = ({ )} { diff --git a/ui-packages/web/src/features/reader/xlsx-reader/sheet-grid.tsx b/ui-packages/web/src/features/reader/xlsx-reader/sheet-grid.tsx index 1d131c2..baa31db 100644 --- a/ui-packages/web/src/features/reader/xlsx-reader/sheet-grid.tsx +++ b/ui-packages/web/src/features/reader/xlsx-reader/sheet-grid.tsx @@ -1,13 +1,51 @@ import { useVirtualizer } from '@tanstack/react-virtual' -import { type RefObject, useLayoutEffect, useMemo } from 'react' -import { cellText, clampColumns, columnLabel, type SheetRow } from '../../../formats/xlsx' +import { type CSSProperties, type RefObject, useLayoutEffect, useMemo } from 'react' +import { + type CellRange, + cellText, + clampColumns, + columnLabel, + type SheetRow, +} from '../../../formats/xlsx' import styles from './style.module.scss' // The virtualizer places rows by this height, so the stylesheet has to use the same number. const rowHeight = 30 +const between = (start: number, end: number) => + Array.from({ length: Math.max(0, end - start + 1) }, (_, index) => start + index) + +// A merged block reads as one cell: each cell drops the borders it shares with the block, and +// the value in the top-left cell runs across the block's shown columns. A block reaching past +// the grid keeps the grid's own edge. Keyed by "row:column". +const mergedCells = (merges: readonly CellRange[], rows: number, columns: number) => + new Map( + merges.flatMap(merge => { + const lastRow = Math.min(merge.endRow, rows) + const lastColumn = Math.min(merge.endColumn, columns) + return between(merge.startRow, lastRow).flatMap(row => + between(merge.startColumn, lastColumn).map(column => { + const anchor = row === merge.startRow && column === merge.startColumn + const className = [ + anchor && styles.mergedAnchor, + column < lastColumn && styles.mergedRight, + row < lastRow && styles.mergedBottom, + ] + return [ + `${row}:${column}`, + { + className: className.filter(Boolean).join(' '), + span: anchor ? lastColumn - column + 1 : undefined, + }, + ] as const + }), + ) + }), + ) + type SheetGridProps = { rows: readonly SheetRow[] + merges?: readonly CellRange[] active: boolean // Where the grid returns to when it is shown; a hidden tab loses its scroll offset. scrollTop: number @@ -18,6 +56,7 @@ type SheetGridProps = { export const SheetGrid = ({ rows, + merges, active, scrollTop, onScrollTopChange, @@ -30,6 +69,10 @@ export const SheetGrid = ({ () => Array.from({ length: columns }, (_, column) => columnLabel(column)), [columns], ) + const merged = useMemo( + () => mergedCells(merges ?? [], rows.length, columns), + [merges, rows.length, columns], + ) const virtualizer = useVirtualizer({ count: rows.length, @@ -85,9 +128,20 @@ export const SheetGrid = ({ {item.index + 1} - {labels.map((label, column) => ( - {cellText(rows[item.index]?.[column] ?? null)} - ))} + {labels.map((label, column) => { + const text = cellText(rows[item.index]?.[column] ?? null) + const cell = merged.get(`${item.index + 1}:${column + 1}`) + if (!cell) return {text} + return ( + + {cell.span ? {text} : text} + + ) + })} ))} {after > 0 && } diff --git a/ui-packages/web/src/features/reader/xlsx-reader/style.module.scss b/ui-packages/web/src/features/reader/xlsx-reader/style.module.scss index 5520794..63a0b45 100644 --- a/ui-packages/web/src/features/reader/xlsx-reader/style.module.scss +++ b/ui-packages/web/src/features/reader/xlsx-reader/style.module.scss @@ -1,3 +1,6 @@ +// A merged block spans several cells, so its text is sized in this unit too. +$cell-width: 160px; + .reader { display: flex; flex-direction: column; @@ -69,8 +72,8 @@ height: var(--row-height); box-sizing: border-box; padding: 0 10px; - width: 160px; - max-width: 160px; + width: $cell-width; + max-width: $cell-width; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; @@ -107,6 +110,27 @@ thead .rowNumber { z-index: 3; } + + .mergedRight { + border-right-color: transparent; + } + + .mergedBottom { + border-bottom-color: transparent; + } + + // The cell keeps the grid's width; its text takes the width of the whole block instead. + .mergedAnchor { + overflow: visible; + text-overflow: clip; + + > span { + display: block; + width: calc(var(--span) * #{$cell-width} - 20px); + overflow: hidden; + text-overflow: ellipsis; + } + } } .empty { diff --git a/ui-packages/web/src/formats/xlsx-package.test.ts b/ui-packages/web/src/formats/xlsx-package.test.ts new file mode 100644 index 0000000..f67d21e --- /dev/null +++ b/ui-packages/web/src/formats/xlsx-package.test.ts @@ -0,0 +1,73 @@ +import JSZip from 'jszip' +import { expect, it } from 'vitest' +import { readSpreadsheet } from './xlsx' + +const relationship = (id: string, type: string, target: string) => + `` + +// A minimal workbook: one sheet, its styles, and inline strings for text. +const workbook = async (sheetData: string, mergeCells: string) => { + const zip = new JSZip() + zip.file( + '[Content_Types].xml', + '', + ) + zip.file( + '_rels/.rels', + `${relationship('rId1', 'officeDocument', 'xl/workbook.xml')}`, + ) + zip.file( + 'xl/workbook.xml', + '', + ) + zip.file( + 'xl/_rels/workbook.xml.rels', + `${relationship('rId1', 'worksheet', 'worksheets/sheet1.xml')}${relationship('rId2', 'styles', 'styles.xml')}`, + ) + zip.file( + 'xl/styles.xml', + '', + ) + zip.file( + 'xl/worksheets/sheet1.xml', + `${sheetData}${mergeCells}`, + ) + return new Blob([await zip.generateAsync({ type: 'arraybuffer' })]) +} + +const text = (reference: string, value: string) => + `${value}` +const number = (reference: string, value: number, style = 0) => + `${value}` + +it('reads cells as the sheet shows them, with errors, unsolved formulas and merges', async () => { + const blob = await workbook( + `${text('A1', 'Quarter')}${text('D1', 'Check')}${text('E1', 'Sum')}` + + `${number('A2', 0.153, 1)}${number('B2', 12345.6, 2)}${number('C2', 1234567.891, 3)}` + + '1/0#DIV/0!SUM(A2:C2)' + + `${number('A3', 2.3456, 4)}${number('B3', 123456789012)}${number('C3', 46085, 5)}` + + '#REF!' + + `${number('A4', 7, 6)}${number('B4', 1234.5, 7)}`, + '', + ) + + expect(await readSpreadsheet(blob)).toEqual([ + { + name: 'Q3', + rows: [ + ['Quarter', null, null, 'Check', 'Sum'], + ['15.3%', '¥12,345.60', '1,234,567.89', '#DIV/0!', '=SUM(A2:C2)'], + // A plain number keeps every digit, a date stays a date, and an error past the last + // column the parser kept still lands in its own. + ['2.35', 123456789012, new Date('2026-03-04T00:00:00Z'), null, null, '#REF!'], + // A format the formatter cannot read keeps the number; one that pads to align its + // column comes without the padding. + [7, '1,234.50', null, null, null], + ], + merges: [ + { startRow: 1, endRow: 1, startColumn: 1, endColumn: 3 }, + { startRow: 2, endRow: 3, startColumn: 4, endColumn: 4 }, + ], + }, + ]) +}) diff --git a/ui-packages/web/src/formats/xlsx-package.ts b/ui-packages/web/src/formats/xlsx-package.ts new file mode 100644 index 0000000..6e14549 --- /dev/null +++ b/ui-packages/web/src/formats/xlsx-package.ts @@ -0,0 +1,122 @@ +import JSZip from 'jszip' +import { format, isDateFormat, isValidFormat } from 'numfmt' + +export type SheetDetails = { + // Cells the parser leaves blank or shows without their number format, by address. + cells: readonly { reference: string; text: string }[] + merges: readonly string[] +} + +const relationshipsNamespace = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' + +// The built-in formats a number can carry without the workbook spelling them out. Dates are +// left out: the parser already reads those as dates. +const builtInFormats = new Map([ + ['1', '0'], + ['2', '0.00'], + ['3', '#,##0'], + ['4', '#,##0.00'], + ['9', '0%'], + ['10', '0.00%'], + ['11', '0.00E+00'], + ['12', '# ?/?'], + ['13', '# ??/??'], + ['37', '#,##0 ;(#,##0)'], + ['38', '#,##0 ;[Red](#,##0)'], + ['39', '#,##0.00;(#,##0.00)'], + ['40', '#,##0.00;[Red](#,##0.00)'], + ['48', '##0.0E+0'], +]) + +const elements = (root: Document | Element, name: string) => + Array.from(root.getElementsByTagName(name)) + +const parse = async (zip: JSZip, path: string) => { + const entry = zip.file(path) + return entry && new DOMParser().parseFromString(await entry.async('string'), 'application/xml') +} + +// A relationship target is relative to xl/ unless it starts at the package root. +const sheetPaths = async (zip: JSZip) => { + const [workbook, relationships] = await Promise.all([ + parse(zip, 'xl/workbook.xml'), + parse(zip, 'xl/_rels/workbook.xml.rels'), + ]) + if (!workbook || !relationships) return [] + const targets = new Map( + elements(relationships, 'Relationship').map(relationship => { + const target = relationship.getAttribute('Target') ?? '' + return [ + relationship.getAttribute('Id'), + target.startsWith('/') ? target.slice(1) : `xl/${target}`, + ] + }), + ) + return elements(workbook, 'sheet').flatMap(sheet => { + const path = targets.get(sheet.getAttributeNS(relationshipsNamespace, 'id')) + return path ? [{ name: sheet.getAttribute('name') ?? '', path }] : [] + }) +} + +// The number format of each cell style, by the style's position, which is what a cell names. +const styleFormats = async (zip: JSZip) => { + const styles = await parse(zip, 'xl/styles.xml') + if (!styles) return [] + const custom = new Map( + elements(styles, 'numFmt').map(format => [ + format.getAttribute('numFmtId'), + format.getAttribute('formatCode'), + ]), + ) + const cellStyles = elements(styles, 'cellXfs')[0] + if (!cellStyles) return [] + return elements(cellStyles, 'xf').map(style => { + const id = style.getAttribute('numFmtId') ?? '0' + return custom.get(id) ?? builtInFormats.get(id) + }) +} + +// Excel shows General numbers past eleven digits in scientific notation, which would cost an +// account or phone number its digits, so those keep the plain value the parser gives, as does +// a format the formatter cannot read. The padding that aligns a column is not part of the value. +const shownNumber = (value: string, code: string | null | undefined) => + code && code !== 'General' && isValidFormat(code) && !isDateFormat(code) + ? format(code, Number(value)).trim() + : null + +// The parser leaves error cells and formulas without a saved result blank; this never +// recalculates, so it says what the file holds. +const cellDetail = (cell: Element, formats: readonly (string | null | undefined)[]) => { + // Some writers leave an empty where Excel writes none. + const value = elements(cell, 'v')[0]?.textContent || undefined + const type = cell.getAttribute('t') + if (type === 'e') return value ?? null + const formula = elements(cell, 'f')[0] + if (formula && value === undefined) + return formula.textContent ? `=${formula.textContent}` : '(formula not calculated)' + if (value !== undefined && (type === null || type === 'n')) + return shownNumber(value, formats[Number(cell.getAttribute('s') ?? 0)]) + return null +} + +const readDetails = (sheet: Document, formats: readonly (string | null | undefined)[]) => ({ + cells: elements(sheet, 'c').flatMap(cell => { + const text = cellDetail(cell, formats) + const reference = cell.getAttribute('r') + return text !== null && reference ? [{ reference, text }] : [] + }), + merges: elements(sheet, 'mergeCell').flatMap(merge => merge.getAttribute('ref') ?? []), +}) + +/** What each sheet holds beyond the values the parser returns, by sheet name. */ +export const readSheetDetails = async (blob: Blob): Promise> => { + const zip = await JSZip.loadAsync(await blob.arrayBuffer()) + const [sheets, formats] = await Promise.all([sheetPaths(zip), styleFormats(zip)]) + const details = await Promise.all( + sheets.map(async ({ name, path }) => { + const sheet = await parse(zip, path) + return [name, sheet ? readDetails(sheet, formats) : { cells: [], merges: [] }] as const + }), + ) + return new Map(details) +} diff --git a/ui-packages/web/src/formats/xlsx.test.ts b/ui-packages/web/src/formats/xlsx.test.ts index a0bfdbf..27f1902 100644 --- a/ui-packages/web/src/formats/xlsx.test.ts +++ b/ui-packages/web/src/formats/xlsx.test.ts @@ -14,6 +14,7 @@ import { const mocks = vi.hoisted(() => ({ read: vi.fn() })) vi.mock('read-excel-file/browser', () => ({ default: mocks.read })) +vi.mock('./xlsx-package', () => ({ readSheetDetails: async () => new Map() })) describe('spreadsheet cells', () => { it('labels columns the way a spreadsheet does, past the first alphabet', () => { @@ -52,6 +53,15 @@ describe('sheet text', () => { expect(text.split('\n').at(-1)).toBe('2\td\t\t') }) + it('names the merged blocks, whose value sits in their top-left cell', () => { + const text = sheetText({ + name: 'S', + rows: [['Q1', null, 'Q2']], + merges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }], + }) + expect(text.split('\n').slice(0, 2)).toEqual(['# S (1 rows × 3 columns)', 'Merged: A1:B1']) + }) + it('says a sheet is empty rather than emitting a bare heading', () => { expect(sheetText({ name: 'Sheet2', rows: [] })).toBe( '# Sheet2 (0 rows × 0 columns)\n\n(empty sheet)', diff --git a/ui-packages/web/src/formats/xlsx.ts b/ui-packages/web/src/formats/xlsx.ts index b57f1c6..cbbc652 100644 --- a/ui-packages/web/src/formats/xlsx.ts +++ b/ui-packages/web/src/formats/xlsx.ts @@ -1,6 +1,9 @@ +import type { SheetDetails } from './xlsx-package' + export type SheetCell = string | number | boolean | Date | null export type SheetRow = readonly SheetCell[] -export type Worksheet = { name: string; rows: readonly SheetRow[] } +// A merged block's value sits in its top-left cell; the rest of the block is empty. +export type Worksheet = { name: string; rows: readonly SheetRow[]; merges?: readonly CellRange[] } // A wide sheet is rare — nine in ten stay under 35 columns — and rendering hundreds of them // costs far more than it shows. The agent still reads every column. @@ -50,6 +53,9 @@ export const parseRange = (text: string): CellRange | null => { } } +export const rangeLabel = (range: CellRange) => + `${columnLabel(range.startColumn - 1)}${range.startRow}:${columnLabel(range.endColumn - 1)}${range.endRow}` + export const columnCount = (rows: readonly SheetRow[]) => rows.reduce((widest, row) => Math.max(widest, row.length), 0) @@ -91,7 +97,8 @@ export const sheetText = (sheet: Worksheet) => { ...Array.from({ length: columns }, (_, column) => cellText(row[column] ?? null)), ].join('\t'), ) - return [heading, letters.join('\t'), ...body].join('\n') + const merged = sheet.merges?.length ? [`Merged: ${sheet.merges.map(rangeLabel).join(', ')}`] : [] + return [heading, ...merged, letters.join('\t'), ...body].join('\n') } export const sheetExtent = (sheet: Worksheet) => { @@ -124,8 +131,30 @@ export const selectCells = (sheet: Worksheet, range: CellRange): CellSelection = // The line-addressable view of the whole workbook, used by the generic read and search tools. export const workbookText = (sheets: readonly Worksheet[]) => sheets.map(sheetText).join('\n\n') +// The parser drops empty rows and columns at the end of a sheet, so a recovered cell can lie +// past the rows it returns. +const withDetails = (name: string, rows: readonly SheetRow[], details?: SheetDetails) => { + if (!details) return { name, rows } + const filled = rows.map(row => [...row]) + for (const { reference, text } of details.cells) { + const cell = parseRange(reference) + if (!cell) continue + while (filled.length < cell.startRow) filled.push([]) + const row = filled[cell.startRow - 1] ?? [] + while (row.length < cell.startColumn - 1) row.push(null) + row[cell.startColumn - 1] = text + } + const merges = details.merges.flatMap(merge => parseRange(merge) ?? []) + return { name, rows: filled, ...(merges.length ? { merges } : {}) } +} + export const readSpreadsheet = async (blob: Blob): Promise => { - const { default: readXlsxFile } = await import('read-excel-file/browser') - const sheets = await readXlsxFile(blob) - return sheets.map(sheet => ({ name: sheet.sheet, rows: sheet.data as SheetRow[] })) + const [{ default: readXlsxFile }, { readSheetDetails }] = await Promise.all([ + import('read-excel-file/browser'), + import('./xlsx-package'), + ]) + const [sheets, details] = await Promise.all([readXlsxFile(blob), readSheetDetails(blob)]) + return sheets.map(sheet => + withDetails(sheet.sheet, sheet.data as SheetRow[], details.get(sheet.sheet)), + ) }