Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions ui-packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand Down
5 changes: 3 additions & 2 deletions ui-packages/web/src/features/assistant/xlsx/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
13 changes: 11 additions & 2 deletions ui-packages/web/src/features/assistant/xlsx/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand All @@ -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'] },
],
})
})
Expand All @@ -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('数据')
})

Expand Down
11 changes: 11 additions & 0 deletions ui-packages/web/src/features/assistant/xlsx/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
type CellRange,
columnCount,
parseRange,
rangeLabel,
selectCells,
sheetExtent,
type Worksheet,
Expand Down Expand Up @@ -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',
Expand All @@ -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) } : {}),
})),
}
},
Expand Down Expand Up @@ -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,
Expand All @@ -88,6 +98,7 @@ export const createXlsxTools = (xlsx: XlsxRuntime) => [
row: selection.startRow + index,
cells,
})),
...(merged.length ? { merged } : {}),
...(nextRow <= lastRow ? { nextRow } : {}),
}
}
Expand Down
5 changes: 3 additions & 2 deletions ui-packages/web/src/features/reader/xlsx-reader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <div className="preview-state">Opening {document.path}…</div>
Expand Down Expand Up @@ -120,7 +120,8 @@ export const XlsxReader = ({
</div>
)}
<SheetGrid
rows={rows}
rows={sheet?.rows ?? []}
merges={sheet?.merges}
active={active}
scrollTop={place.current}
onScrollTopChange={scrollTop => {
Expand Down
64 changes: 59 additions & 5 deletions ui-packages/web/src/features/reader/xlsx-reader/sheet-grid.tsx
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -18,6 +56,7 @@ type SheetGridProps = {

export const SheetGrid = ({
rows,
merges,
active,
scrollTop,
onScrollTopChange,
Expand All @@ -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,
Expand Down Expand Up @@ -85,9 +128,20 @@ export const SheetGrid = ({
<th scope="row" className={styles.rowNumber}>
{item.index + 1}
</th>
{labels.map((label, column) => (
<td key={label}>{cellText(rows[item.index]?.[column] ?? null)}</td>
))}
{labels.map((label, column) => {
const text = cellText(rows[item.index]?.[column] ?? null)
const cell = merged.get(`${item.index + 1}:${column + 1}`)
if (!cell) return <td key={label}>{text}</td>
return (
<td
key={label}
className={cell.className}
style={cell.span ? ({ '--span': cell.span } as CSSProperties) : undefined}
>
{cell.span ? <span>{text}</span> : text}
</td>
)
})}
</tr>
))}
{after > 0 && <tr aria-hidden style={{ height: after }} />}
Expand Down
28 changes: 26 additions & 2 deletions ui-packages/web/src/features/reader/xlsx-reader/style.module.scss
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
73 changes: 73 additions & 0 deletions ui-packages/web/src/formats/xlsx-package.test.ts
Original file line number Diff line number Diff line change
@@ -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) =>
`<Relationship Id="${id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="${target}"/>`

// 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',
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/></Types>',
)
zip.file(
'_rels/.rels',
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship('rId1', 'officeDocument', 'xl/workbook.xml')}</Relationships>`,
)
zip.file(
'xl/workbook.xml',
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Q3" sheetId="1" r:id="rId1"/></sheets></workbook>',
)
zip.file(
'xl/_rels/workbook.xml.rels',
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship('rId1', 'worksheet', 'worksheets/sheet1.xml')}${relationship('rId2', 'styles', 'styles.xml')}</Relationships>`,
)
zip.file(
'xl/styles.xml',
'<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="5"><numFmt numFmtId="164" formatCode="0.0%"/><numFmt numFmtId="165" formatCode="[$¥-804]#,##0.00"/><numFmt numFmtId="166" formatCode="yyyy-mm-dd"/><numFmt numFmtId="167" formatCode="0.0.0%%[["/><numFmt numFmtId="168" formatCode="_(* #,##0.00_);_(* \\(#,##0.00\\);_(* &quot;-&quot;??_);_(@_)"/></numFmts><cellXfs count="8"><xf numFmtId="0"/><xf numFmtId="164"/><xf numFmtId="165"/><xf numFmtId="4"/><xf numFmtId="2"/><xf numFmtId="166"/><xf numFmtId="167"/><xf numFmtId="168"/></cellXfs></styleSheet>',
)
zip.file(
'xl/worksheets/sheet1.xml',
`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${sheetData}</sheetData>${mergeCells}</worksheet>`,
)
return new Blob([await zip.generateAsync({ type: 'arraybuffer' })])
}

const text = (reference: string, value: string) =>
`<c r="${reference}" t="inlineStr"><is><t>${value}</t></is></c>`
const number = (reference: string, value: number, style = 0) =>
`<c r="${reference}" s="${style}"><v>${value}</v></c>`

it('reads cells as the sheet shows them, with errors, unsolved formulas and merges', async () => {
const blob = await workbook(
`<row r="1">${text('A1', 'Quarter')}${text('D1', 'Check')}${text('E1', 'Sum')}</row>` +
`<row r="2">${number('A2', 0.153, 1)}${number('B2', 12345.6, 2)}${number('C2', 1234567.891, 3)}` +
'<c r="D2" t="e"><f>1/0</f><v>#DIV/0!</v></c><c r="E2" s="1"><f>SUM(A2:C2)</f><v></v></c></row>' +
`<row r="3">${number('A3', 2.3456, 4)}${number('B3', 123456789012)}${number('C3', 46085, 5)}` +
'<c r="F3" t="e"><v>#REF!</v></c></row>' +
`<row r="4">${number('A4', 7, 6)}${number('B4', 1234.5, 7)}</row>`,
'<mergeCells count="2"><mergeCell ref="A1:C1"/><mergeCell ref="D2:D3"/></mergeCells>',
)

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 },
],
},
])
})
Loading