Skip to content

Build your personal knowledge base with Trilium Notes

feat(spreadsheet): prototype for parsing from XLSX

Elian Doran1cf0dca04452
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts
new file mode 100644
index 0000000000..6386e59e8e
--- /dev/null
+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts
@@ -0,0 +1,164 @@
+import ExcelJS from "exceljs";
+import { describe, expect, it } from "vitest";
+
+import { parseXlsxToWorkbook } from "./parse_from_xlsx.js";
+import {
+ BorderStyle,
+ CellValueType,
+ HorizontalAlign,
+ type ICellData,
+ type IWorksheetData,
+ VerticalAlign,
+ WrapStrategy
+} from "./workbook_model.js";
+
+/** Build an xlsx in memory, parse it back, and return the requested sheet's Univer data. */
+async function roundTrip(build: (wb: ExcelJS.Workbook) => void, sheetIndex = 0): Promise<IWorksheetData> {
+ const wb = new ExcelJS.Workbook();
+ build(wb);
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+ const id = workbook.sheetOrder[sheetIndex];
+ return workbook.sheets[id];
+}
+
+/** Convenience: the single styled cell at A1 (row 0, col 0). */
+function cellA1(sheet: IWorksheetData): ICellData | undefined {
+ return sheet.cellData[0]?.[0];
+}
+
+describe("parseXlsxToWorkbook", () => {
+ it("reads string, number and boolean values with their cell types", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("Ledger");
+ ws.getCell("A1").value = "Hello";
+ ws.getCell("B1").value = 42;
+ ws.getCell("C1").value = true;
+ });
+
+ expect(sheet.name).toBe("Ledger");
+ expect(sheet.cellData[0][0]).toMatchObject({ v: "Hello", t: CellValueType.STRING });
+ expect(sheet.cellData[0][1]).toMatchObject({ v: 42, t: CellValueType.NUMBER });
+ expect(sheet.cellData[0][2]).toMatchObject({ v: true, t: CellValueType.BOOLEAN });
+ });
+
+ it("reads a formula and re-adds the leading '='", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = { formula: "SUM(B1:B2)", result: 7 } as ExcelJS.CellFormulaValue;
+ });
+ expect(cellA1(sheet)).toMatchObject({ f: "=SUM(B1:B2)", v: 7, t: CellValueType.NUMBER });
+ });
+
+ it("reads font styling and an explicit ARGB color", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const cell = ws.getCell("A1");
+ cell.value = "f";
+ cell.font = { name: "Arial", size: 14, bold: true, italic: true, underline: true, strike: true, color: { argb: "FF414657" } };
+ });
+ expect(cellA1(sheet)?.s).toMatchObject({
+ ff: "Arial", fs: 14, bl: 1, it: 1, ul: { s: 1 }, st: { s: 1 }, cl: { rgb: "#414657" }
+ });
+ });
+
+ it("reads a solid fill into the background color", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const cell = ws.getCell("A1");
+ cell.value = "x";
+ cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFF9F9F9" } };
+ });
+ expect(cellA1(sheet)?.s).toMatchObject({ bg: { rgb: "#F9F9F9" } });
+ });
+
+ it("reads alignment and wrap", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const cell = ws.getCell("A1");
+ cell.value = "x";
+ cell.alignment = { horizontal: "right", vertical: "middle", wrapText: true };
+ });
+ expect(cellA1(sheet)?.s).toMatchObject({
+ ht: HorizontalAlign.RIGHT, vt: VerticalAlign.MIDDLE, tb: WrapStrategy.WRAP
+ });
+ });
+
+ it("maps exceljs border styles back to the Univer enum", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const cell = ws.getCell("A1");
+ cell.value = "b";
+ cell.border = {
+ top: { style: "thin", color: { argb: "FF111111" } },
+ right: { style: "medium", color: { argb: "FF222222" } },
+ bottom: { style: "thick", color: { argb: "FF333333" } },
+ left: { style: "dotted", color: { argb: "FF444444" } }
+ };
+ });
+ expect(cellA1(sheet)?.s).toMatchObject({
+ bd: {
+ t: { s: BorderStyle.THIN, cl: { rgb: "#111111" } },
+ r: { s: BorderStyle.MEDIUM },
+ b: { s: BorderStyle.THICK },
+ l: { s: BorderStyle.DOTTED }
+ }
+ });
+ });
+
+ it("reads the number-format pattern verbatim", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const cell = ws.getCell("A1");
+ cell.value = 1234.5;
+ cell.numFmt = "#,##0.00;[Red]#,##0.00";
+ });
+ expect(cellA1(sheet)?.s).toMatchObject({ n: { pattern: "#,##0.00;[Red]#,##0.00" } });
+ });
+
+ it("reads merges as 0-based inclusive ranges", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = "merged";
+ ws.mergeCells("A1:B2");
+ });
+ expect(sheet.mergeData).toEqual([{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }]);
+ });
+
+ it("converts column width (chars) and row height (points) back to pixels", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = "x";
+ ws.getColumn(1).width = 16;
+ ws.getRow(1).height = 30;
+ });
+ // 16 chars -> 16*7+5 = 117px; 30pt -> 30/0.75 = 40px.
+ expect(sheet.columnData?.[0]?.w).toBeCloseTo(117, 1);
+ expect(sheet.rowData?.[0]?.h).toBeCloseTo(40, 1);
+ });
+
+ it("flags hidden sheets, rows and columns", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("Secret", { state: "hidden" });
+ ws.getCell("A1").value = "x";
+ ws.getColumn(1).hidden = true;
+ ws.getRow(1).hidden = true;
+ });
+ expect(sheet.hidden).toBe(1);
+ expect(sheet.columnData?.[0]?.hd).toBe(1);
+ expect(sheet.rowData?.[0]?.hd).toBe(1);
+ });
+
+ it("preserves sheet order across multiple sheets", async () => {
+ const wb = new ExcelJS.Workbook();
+ wb.addWorksheet("First").getCell("A1").value = "1";
+ wb.addWorksheet("Second").getCell("A1").value = "2";
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+ expect(workbook.sheetOrder.map((id) => workbook.sheets[id].name)).toEqual(["First", "Second"]);
+ });
+
+ it("throws on a non-xlsx buffer", async () => {
+ await expect(parseXlsxToWorkbook(new Uint8Array([1, 2, 3]))).rejects.toThrow(/parse/i);
+ });
+});
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
new file mode 100644
index 0000000000..03035eb83c
--- /dev/null
+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
@@ -0,0 +1,512 @@
+/**
+ * Parses an `.xlsx` file (OOXML) into a UniversJS workbook JSON structure — the inverse of
+ * `render_to_xlsx`. The result matches the `PersistedData` shape that a spreadsheet note
+ * stores and that the editor loads via `univerAPI.createWorkbook(...)`, so the output can be
+ * stringified straight into note content.
+ *
+ * Like the exporter, the mapping is near-1:1: values, formulas, number formats, fonts, fills,
+ * alignment, borders, merges and row/column sizing all invert their export counterparts. The
+ * heavy lifting (unzip + XML) is delegated to `exceljs`.
+ *
+ * Known fidelity gaps (Excel features Univer's cell model — and our exporter — don't carry):
+ * conditional formatting, data validation, filters, charts, embedded images, comments,
+ * frozen panes and defined names are dropped. Rich text is flattened to plain text and
+ * hyperlinks keep their display text but lose the link. Theme/indexed colors are resolved
+ * against the standard Office palette (see `THEME_COLORS`), which is approximate when the
+ * file ships a custom theme.
+ */
+
+import ExcelJS from "exceljs";
+
+import {
+ BorderStyle,
+ CellValueType,
+ HorizontalAlign,
+ type IBorderData,
+ type IBorderStyleData,
+ type ICellData,
+ type IColumnData,
+ type IRange,
+ type IRowData,
+ type IStyleData,
+ type IWorksheetData,
+ type PersistedData,
+ VerticalAlign,
+ WrapStrategy
+} from "./workbook_model.js";
+
+/** Univer's default grid size for a fresh sheet; imported sheets are grown to fit their data. */
+const DEFAULT_ROW_COUNT = 1000;
+const DEFAULT_COLUMN_COUNT = 20;
+
+/**
+ * Reads an `.xlsx` binary and produces a UniversJS workbook. Hidden sheets/rows/columns are
+ * preserved and flagged hidden. Styles are emitted inline on each cell (Univer accepts either
+ * inline objects or a shared `styles` table; inline keeps the parser stateless). Throws if the
+ * buffer is not a readable workbook.
+ */
+export async function parseXlsxToWorkbook(input: ArrayBuffer | Uint8Array): Promise<PersistedData> {
+ const wb = new ExcelJS.Workbook();
+ try {
+ // exceljs accepts a Node Buffer or an ArrayBuffer; normalize a Uint8Array view to its buffer.
+ const buffer = input instanceof Uint8Array ? input.buffer : input;
+ await wb.xlsx.load(buffer as ArrayBuffer);
+ } catch {
+ throw new Error("Unable to parse spreadsheet file.");
+ }
+
+ const sheetOrder: string[] = [];
+ const sheets: Record<string, IWorksheetData> = {};
+
+ wb.eachSheet((ws, sheetIndex) => {
+ // Deterministic ids keyed off position; the workbook id/locale are reassigned on load
+ // (see persistence.tsx) and sheet view state keys off this id, so stability is all we need.
+ const id = `sheet-${sheetIndex}`;
+ sheetOrder.push(id);
+ sheets[id] = readSheet(ws, id);
+ });
+
+ return {
+ version: 1,
+ workbook: {
+ sheetOrder,
+ styles: {},
+ sheets
+ }
+ };
+}
+
+function readSheet(ws: ExcelJS.Worksheet, id: string): IWorksheetData {
+ const cellData = readCells(ws);
+ const mergeData = readMerges(ws);
+ const { rowData, maxRow } = readRows(ws);
+ const { columnData, maxCol } = readColumns(ws);
+
+ const sheet: IWorksheetData = {
+ id,
+ name: ws.name,
+ cellData,
+ rowData,
+ columnData,
+ mergeData,
+ // Grow the grid past Univer's defaults when the data needs it, so nothing is clipped.
+ rowCount: Math.max(DEFAULT_ROW_COUNT, maxRow + 1),
+ columnCount: Math.max(DEFAULT_COLUMN_COUNT, maxCol + 1),
+ // exceljs reports a hidden sheet as state "hidden"/"veryHidden".
+ hidden: ws.state && ws.state !== "visible" ? 1 : 0,
+ showGridlines: ws.views?.[0]?.showGridLines === false ? 0 : 1
+ };
+
+ if (isFiniteNumber(ws.properties?.defaultColWidth)) {
+ sheet.defaultColumnWidth = excelWidthToPx(ws.properties.defaultColWidth);
+ }
+ if (isFiniteNumber(ws.properties?.defaultRowHeight)) {
+ sheet.defaultRowHeight = pointsToPx(ws.properties.defaultRowHeight);
+ }
+
+ return sheet;
+}
+
+function readCells(ws: ExcelJS.Worksheet): Record<number, Record<number, ICellData>> {
+ const cellData: Record<number, Record<number, ICellData>> = {};
+
+ ws.eachRow({ includeEmpty: false }, (row, rowNumber) => {
+ row.eachCell({ includeEmpty: false }, (cell, colNumber) => {
+ const data = readCell(cell);
+ if (!data) return;
+ const r = rowNumber - 1;
+ const c = colNumber - 1;
+ (cellData[r] ??= {})[c] = data;
+ });
+ });
+
+ return cellData;
+}
+
+function readCell(cell: ExcelJS.Cell): ICellData | null {
+ const data: ICellData = {};
+ applyCellValue(data, cell);
+
+ const style = readStyle(cell);
+ if (style) data.s = style;
+
+ // Drop cells that carry neither a value, a formula nor a style.
+ if (data.v == null && data.f == null && data.s == null) return null;
+ return data;
+}
+
+function applyCellValue(data: ICellData, cell: ExcelJS.Cell): void {
+ // Formula cells: re-add the leading "=" the exporter strips, and carry the cached result.
+ if (cell.type === ExcelJS.ValueType.Formula) {
+ data.f = `=${cell.formula}`;
+ assignPrimitive(data, cell.result);
+ return;
+ }
+
+ switch (cell.type) {
+ case ExcelJS.ValueType.Number:
+ data.v = cell.value as number;
+ data.t = CellValueType.NUMBER;
+ break;
+ case ExcelJS.ValueType.Boolean:
+ data.v = cell.value as boolean;
+ data.t = CellValueType.BOOLEAN;
+ break;
+ case ExcelJS.ValueType.Date:
+ data.v = dateToSerial(cell.value as Date);
+ data.t = CellValueType.NUMBER;
+ break;
+ case ExcelJS.ValueType.Hyperlink:
+ // Keep the display text; the link itself has no inline Univer equivalent.
+ data.v = String((cell.value as ExcelJS.CellHyperlinkValue)?.text ?? "");
+ data.t = CellValueType.STRING;
+ break;
+ case ExcelJS.ValueType.RichText:
+ data.v = flattenRichText(cell.value as ExcelJS.CellRichTextValue);
+ data.t = CellValueType.STRING;
+ break;
+ case ExcelJS.ValueType.Error:
+ data.v = String((cell.value as ExcelJS.CellErrorValue)?.error ?? "#ERROR!");
+ data.t = CellValueType.FORCE_STRING;
+ break;
+ case ExcelJS.ValueType.String:
+ data.v = cell.value as string;
+ data.t = CellValueType.STRING;
+ break;
+ default:
+ // Null/Merge/empty — nothing to carry.
+ break;
+ }
+}
+
+/** Maps a formula's cached result (number/bool/string/date) onto the cell value + type. */
+function assignPrimitive(data: ICellData, result: ExcelJS.Cell["result"]): void {
+ if (result == null) return;
+ if (typeof result === "number") { data.v = result; data.t = CellValueType.NUMBER; return; }
+ if (typeof result === "boolean") { data.v = result; data.t = CellValueType.BOOLEAN; return; }
+ if (result instanceof Date) { data.v = dateToSerial(result); data.t = CellValueType.NUMBER; return; }
+ if (typeof result === "object" && "error" in result) { data.v = String(result.error); data.t = CellValueType.FORCE_STRING; return; }
+ data.v = String(result);
+ data.t = CellValueType.STRING;
+}
+
+function flattenRichText(value: ExcelJS.CellRichTextValue): string {
+ return (value?.richText ?? []).map((run) => run.text).join("");
+}
+
+function readStyle(cell: ExcelJS.Cell): IStyleData | null {
+ const style: IStyleData = {};
+ let any = false;
+
+ const font = readFont(cell.font);
+ if (font) { Object.assign(style, font); any = true; }
+
+ const bg = excelColorToRgb(solidFillColor(cell.fill));
+ if (bg) { style.bg = { rgb: bg }; any = true; }
+
+ const alignment = readAlignment(cell.alignment);
+ if (alignment) { Object.assign(style, alignment); any = true; }
+
+ const border = readBorder(cell.border);
+ if (border) { style.bd = border; any = true; }
+
+ if (cell.numFmt) { style.n = { pattern: cell.numFmt }; any = true; }
+
+ return any ? style : null;
+}
+
+function readFont(font: Partial<ExcelJS.Font> | undefined): Partial<IStyleData> | null {
+ if (!font) return null;
+ const out: Partial<IStyleData> = {};
+ let any = false;
+
+ if (font.name) { out.ff = font.name; any = true; }
+ if (isFiniteNumber(font.size)) { out.fs = font.size; any = true; }
+ if (font.bold) { out.bl = 1; any = true; }
+ if (font.italic) { out.it = 1; any = true; }
+ if (font.underline) { out.ul = { s: 1 }; any = true; }
+ if (font.strike) { out.st = { s: 1 }; any = true; }
+
+ const color = excelColorToRgb(font.color);
+ if (color) { out.cl = { rgb: color }; any = true; }
+
+ return any ? out : null;
+}
+
+function readAlignment(alignment: Partial<ExcelJS.Alignment> | undefined): Partial<IStyleData> | null {
+ if (!alignment) return null;
+ const out: Partial<IStyleData> = {};
+ let any = false;
+
+ const ht = horizontalAlign(alignment.horizontal);
+ if (ht) { out.ht = ht; any = true; }
+
+ const vt = verticalAlign(alignment.vertical);
+ if (vt) { out.vt = vt; any = true; }
+
+ if (alignment.wrapText) { out.tb = WrapStrategy.WRAP; any = true; }
+
+ if (alignment.textRotation === "vertical") {
+ out.tr = { v: 1 }; any = true;
+ } else if (isFiniteNumber(alignment.textRotation) && alignment.textRotation !== 0) {
+ out.tr = { a: alignment.textRotation }; any = true;
+ }
+
+ return any ? out : null;
+}
+
+function readBorder(border: Partial<ExcelJS.Borders> | undefined): IBorderData | null {
+ if (!border) return null;
+ const out: IBorderData = {};
+ let any = false;
+
+ for (const [univerSide, excelSide] of [["t", "top"], ["r", "right"], ["b", "bottom"], ["l", "left"]] as const) {
+ const side = readBorderSide(border[excelSide]);
+ if (!side) continue;
+ out[univerSide] = side;
+ any = true;
+ }
+
+ return any ? out : null;
+}
+
+function readBorderSide(side: Partial<ExcelJS.Border> | undefined): IBorderStyleData | null {
+ const style = borderStyle(side?.style);
+ if (style == null) return null;
+ const out: IBorderStyleData = { s: style };
+ const color = excelColorToRgb(side?.color);
+ if (color) out.cl = { rgb: color };
+ return out;
+}
+
+function readMerges(ws: ExcelJS.Worksheet): IRange[] {
+ // exceljs exposes merges as A1-style range strings on the worksheet model.
+ const merges = (ws.model as { merges?: string[] })?.merges ?? [];
+ const ranges: IRange[] = [];
+ for (const ref of merges) {
+ const range = parseRange(ref);
+ if (range) ranges.push(range);
+ }
+ return ranges;
+}
+
+function readRows(ws: ExcelJS.Worksheet): { rowData: Record<number, IRowData>; maxRow: number } {
+ const rowData: Record<number, IRowData> = {};
+ let maxRow = 0;
+
+ ws.eachRow({ includeEmpty: false }, (row, rowNumber) => {
+ const index = rowNumber - 1;
+ if (rowNumber > maxRow) maxRow = rowNumber - 1;
+
+ const meta: IRowData = {};
+ if (isFiniteNumber(row.height)) meta.h = pointsToPx(row.height);
+ if (row.hidden) meta.hd = 1;
+ if (meta.h != null || meta.hd != null) rowData[index] = meta;
+ });
+
+ return { rowData, maxRow };
+}
+
+function readColumns(ws: ExcelJS.Worksheet): { columnData: Record<number, IColumnData>; maxCol: number } {
+ const columnData: Record<number, IColumnData> = {};
+ let maxCol = 0;
+
+ // `ws.columns` is null when no column metadata exists; cell-driven width still has no column entry.
+ (ws.columns ?? []).forEach((column, index) => {
+ if (index > maxCol) maxCol = index;
+
+ const meta: IColumnData = {};
+ if (isFiniteNumber(column.width)) meta.w = excelWidthToPx(column.width);
+ if (column.hidden) meta.hd = 1;
+ if (meta.w != null || meta.hd != null) columnData[index] = meta;
+ });
+
+ // The cell pass may reach further right than the declared columns; account for that.
+ maxCol = Math.max(maxCol, ws.actualColumnCount - 1);
+ return { columnData, maxCol };
+}
+
+function horizontalAlign(horizontal: ExcelJS.Alignment["horizontal"] | undefined): HorizontalAlign | null {
+ switch (horizontal) {
+ case "left": return HorizontalAlign.LEFT;
+ case "center": return HorizontalAlign.CENTER;
+ case "right": return HorizontalAlign.RIGHT;
+ default: return null; // fill/justify/distributed/etc. have no Univer equivalent
+ }
+}
+
+function verticalAlign(vertical: ExcelJS.Alignment["vertical"] | undefined): VerticalAlign | null {
+ switch (vertical) {
+ case "top": return VerticalAlign.TOP;
+ case "middle": return VerticalAlign.MIDDLE;
+ case "bottom": return VerticalAlign.BOTTOM;
+ default: return null;
+ }
+}
+
+function borderStyle(style: ExcelJS.BorderStyle | undefined): BorderStyle | null {
+ switch (style) {
+ case "thin": return BorderStyle.THIN;
+ case "hair": return BorderStyle.HAIR;
+ case "dotted": return BorderStyle.DOTTED;
+ case "dashed": return BorderStyle.DASHED;
+ case "dashDot": return BorderStyle.DASH_DOT;
+ case "dashDotDot": return BorderStyle.DASH_DOT_DOT;
+ case "double": return BorderStyle.DOUBLE;
+ case "medium": return BorderStyle.MEDIUM;
+ case "mediumDashed": return BorderStyle.MEDIUM_DASHED;
+ case "mediumDashDot": return BorderStyle.MEDIUM_DASH_DOT;
+ case "mediumDashDotDot": return BorderStyle.MEDIUM_DASH_DOT_DOT;
+ case "slantDashDot": return BorderStyle.SLANT_DASH_DOT;
+ case "thick": return BorderStyle.THICK;
+ default: return null;
+ }
+}
+
+function solidFillColor(fill: ExcelJS.Fill | undefined): Partial<ExcelJS.Color> | undefined {
+ if (!fill || fill.type !== "pattern") return undefined;
+ // "solid" puts the visible color in fgColor; other patterns approximate with the same.
+ return fill.fgColor;
+}
+
+/**
+ * Converts an exceljs color to a `#rrggbb` hex string, or `null` when it can't be resolved.
+ * Handles explicit ARGB and theme colors (resolved against the standard Office palette plus
+ * tint). Indexed (legacy) colors are not handled.
+ */
+function excelColorToRgb(color: Partial<ExcelJS.Color> | undefined): string | null {
+ if (!color) return null;
+ if (typeof color.argb === "string") return argbToHex(color.argb);
+ if (typeof color.theme === "number") {
+ const base = THEME_COLORS[color.theme];
+ if (!base) return null;
+ return applyTint(base, isFiniteNumber(color.tint) ? color.tint : 0);
+ }
+ return null;
+}
+
+/** Converts an `AARRGGBB` string to `#RRGGBB`, dropping the alpha. Fully transparent → null. */
+function argbToHex(argb: string): string | null {
+ const s = argb.trim().toUpperCase();
+ if (/^[0-9A-F]{8}$/.test(s)) {
+ if (s.slice(0, 2) === "00") return null; // transparent
+ return `#${s.slice(2)}`;
+ }
+ if (/^[0-9A-F]{6}$/.test(s)) return `#${s}`;
+ return null;
+}
+
+/**
+ * Standard Office theme palette, indexed the way SpreadsheetML references theme colors in cell
+ * formatting (note the light/dark swap at 0/1 and 2/3 relative to the theme XML order).
+ */
+const THEME_COLORS: string[] = [
+ "#FFFFFF", // 0 — light 1 (background)
+ "#000000", // 1 — dark 1 (text)
+ "#E7E6E6", // 2 — light 2
+ "#44546A", // 3 — dark 2
+ "#4472C4", // 4 — accent 1
+ "#ED7D31", // 5 — accent 2
+ "#A5A5A5", // 6 — accent 3
+ "#FFC000", // 7 — accent 4
+ "#5B9BD5", // 8 — accent 5
+ "#70AD47", // 9 — accent 6
+ "#0563C1", // 10 — hyperlink
+ "#954F72" // 11 — followed hyperlink
+];
+
+/** Applies an OOXML tint (-1..1) to a hex color by shifting its HSL luminance. */
+function applyTint(hex: string, tint: number): string {
+ if (!tint) return hex;
+ const { h, s, l } = rgbToHsl(hex);
+ const lum = tint < 0 ? l * (1 + tint) : l * (1 - tint) + tint;
+ return hslToRgb(h, s, lum);
+}
+
+function rgbToHsl(hex: string): { h: number; s: number; l: number } {
+ const n = hex.replace("#", "");
+ const r = parseInt(n.slice(0, 2), 16) / 255;
+ const g = parseInt(n.slice(2, 4), 16) / 255;
+ const b = parseInt(n.slice(4, 6), 16) / 255;
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const l = (max + min) / 2;
+ if (max === min) return { h: 0, s: 0, l };
+ const d = max - min;
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ let h = 0;
+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
+ else if (max === g) h = (b - r) / d + 2;
+ else h = (r - g) / d + 4;
+ return { h: h / 6, s, l };
+}
+
+function hslToRgb(h: number, s: number, l: number): string {
+ if (s === 0) {
+ const v = clampChannel(l);
+ return `#${v}${v}${v}`;
+ }
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ const p = 2 * l - q;
+ const r = hueToChannel(p, q, h + 1 / 3);
+ const g = hueToChannel(p, q, h);
+ const b = hueToChannel(p, q, h - 1 / 3);
+ return `#${clampChannel(r)}${clampChannel(g)}${clampChannel(b)}`;
+}
+
+function hueToChannel(p: number, q: number, t: number): number {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
+ if (t < 1 / 2) return q;
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
+ return p;
+}
+
+function clampChannel(v: number): string {
+ const byte = Math.round(Math.min(1, Math.max(0, v)) * 255);
+ return byte.toString(16).padStart(2, "0").toUpperCase();
+}
+
+/** Parses an A1-style range ("B2:D5" or a single "A1") into a 0-based inclusive `IRange`. */
+function parseRange(ref: string): IRange | null {
+ const [from, to] = ref.split(":");
+ const start = parseAddress(from);
+ const end = parseAddress(to ?? from);
+ if (!start || !end) return null;
+ return {
+ startRow: Math.min(start.row, end.row),
+ endRow: Math.max(start.row, end.row),
+ startColumn: Math.min(start.col, end.col),
+ endColumn: Math.max(start.col, end.col)
+ };
+}
+
+function parseAddress(addr: string): { row: number; col: number } | null {
+ const m = /^([A-Z]+)(\d+)$/.exec(addr.trim().toUpperCase());
+ if (!m) return null;
+ let col = 0;
+ for (const ch of m[1]) col = col * 26 + (ch.charCodeAt(0) - 64);
+ return { row: Number(m[2]) - 1, col: col - 1 };
+}
+
+/** Excel column width (character units) → pixels; inverse of the exporter's `pxToExcelWidth`. */
+function excelWidthToPx(width: number): number {
+ return width * 7 + 5;
+}
+
+/** Excel row height (points) → pixels; inverse of the exporter's `pxToPoints` (1pt = 1/0.75 px). */
+function pointsToPx(points: number): number {
+ return points / 0.75;
+}
+
+/** Excel serial date (days since 1899-12-30) for a JS Date; inverse of exceljs' date parsing. */
+function dateToSerial(date: Date): number {
+ const EPOCH_OFFSET_DAYS = 25569; // days between 1899-12-30 and 1970-01-01
+ const MS_PER_DAY = 86_400_000;
+ return date.getTime() / MS_PER_DAY + EPOCH_OFFSET_DAYS;
+}
+
+function isFiniteNumber(v: unknown): v is number {
+ return typeof v === "number" && Number.isFinite(v);
+}
diff --git a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
index da00520d44..22ec9a1153 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
@@ -61,6 +61,39 @@ describe("renderSpreadsheetToCsv", () => {
expect(csv).toBe("3");
});
+ it("renders date serials as ISO 8601 (yyyy-mm-dd), not the raw serial", () => {
+ // 46118 is 2026-04-06 in Excel's serial date system.
+ const inlineStyle = renderSpreadsheetToCsv(workbook({
+ 0: { 0: { v: 46118, t: 2, s: { n: { pattern: "m/d/yy" } } } }
+ }));
+ expect(inlineStyle).toBe("2026-04-06");
+
+ // A date pattern referenced from the shared styles table resolves the same way.
+ const sharedStyle = renderSpreadsheetToCsv(workbook(
+ { 0: { 0: { v: 46118, t: 2, s: "d1" } } },
+ {},
+ { styles: { d1: { n: { pattern: "dd/mm/yyyy" } } } }
+ ));
+ expect(sharedStyle).toBe("2026-04-06");
+ });
+
+ it("appends the time portion when the date format carries one", () => {
+ const csv = renderSpreadsheetToCsv(workbook({
+ 0: {
+ 0: { v: 46118.5, t: 2, s: { n: { pattern: "yyyy-mm-dd hh:mm" } } },
+ 1: { v: 46118.5, t: 2, s: { n: { pattern: "m/d/yy h:mm:ss" } } }
+ }
+ }));
+ expect(csv).toBe("2026-04-06 12:00,2026-04-06 12:00:00");
+ });
+
+ it("keeps a non-date numeric cell raw even when it has a number format", () => {
+ const csv = renderSpreadsheetToCsv(workbook({
+ 0: { 0: { v: 1234.5, t: 2, s: { n: { pattern: "#,##0.00" } } } }
+ }));
+ expect(csv).toBe("1234.5");
+ });
+
it("quotes fields containing commas, quotes, or newlines (RFC 4180)", () => {
const csv = renderSpreadsheetToCsv(workbook({
0: { 0: { v: "a,b" }, 1: { v: 'he said "hi"' }, 2: { v: "line1\nline2" } }
diff --git a/packages/commons/src/lib/spreadsheet/render_to_csv.ts b/packages/commons/src/lib/spreadsheet/render_to_csv.ts
index 457af3879a..69539665a3 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_csv.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.ts
@@ -4,20 +4,30 @@
* CSV is a flat, single-sheet, value-only format: it carries no styling, merges, or
* formulas. So this emitter throws away everything the HTML/XLSX emitters preserve and
* keeps only the cell values, laid out as a dense rectangle over the sheet's populated
- * bounds. Formula cells export their cached result (Univer stores it in `v`); numbers and
- * dates export their raw underlying value rather than the formatted display string, which
- * is what downstream CSV consumers expect.
+ * bounds. Formula cells export their cached result (Univer stores it in `v`); most numbers
+ * export their raw underlying value rather than the formatted display string, which is what
+ * downstream CSV consumers expect.
+ *
+ * Dates are the exception: Univer stores them as serial numbers (e.g. `46118`), which no
+ * CSV consumer recognizes as a date. So date-formatted cells are emitted as ISO 8601
+ * (`yyyy-mm-dd`, plus time when the format carries it) — unambiguous and parsed by Excel,
+ * LibreOffice, etc. — rather than the locale-specific display string or the raw serial.
*
* Because CSV holds a single sheet, the caller picks which one via `sheetId` (e.g. the
* active sheet in the editor); absent that, the first visible sheet is used.
*/
+import { format as formatNumfmt, getFormatDateInfo, isDateFormat } from "numfmt";
+
import {
computeBounds,
getVisibleSheets,
type ICellData,
+ isFiniteNumber,
+ type IStyleData,
type IWorksheetData,
- parseWorkbookData
+ parseWorkbookData,
+ resolveCellStyle
} from "./workbook_model.js";
export interface CsvRenderOptions {
@@ -46,7 +56,7 @@ export function renderSpreadsheetToCsv(jsonContent: string, options: CsvRenderOp
}
const sheet = pickSheet(visibleSheets, options.sheetId);
- return renderSheet(sheet);
+ return renderSheet(sheet, data.workbook.styles ?? {});
}
function pickSheet(visibleSheets: IWorksheetData[], sheetId: string | undefined): IWorksheetData {
@@ -57,7 +67,7 @@ function pickSheet(visibleSheets: IWorksheetData[], sheetId: string | undefined)
return visibleSheets[0];
}
-function renderSheet(sheet: IWorksheetData): string {
+function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData | null>): string {
const { cellData } = sheet;
const bounds = computeBounds(cellData, sheet.mergeData);
if (!bounds) {
@@ -70,7 +80,7 @@ function renderSheet(sheet: IWorksheetData): string {
for (let row = minRow; row <= maxRow; row++) {
const cells: string[] = [];
for (let col = minCol; col <= maxCol; col++) {
- cells.push(escapeCsvField(cellText(cellData[row]?.[col])));
+ cells.push(escapeCsvField(cellText(cellData[row]?.[col], styles)));
}
lines.push(cells.join(","));
}
@@ -79,13 +89,44 @@ function renderSheet(sheet: IWorksheetData): string {
return lines.join("\r\n");
}
-/** Extracts a cell's plain-text value. Formula cells use their cached result (`v`). */
-function cellText(cell: ICellData | undefined): string {
+/**
+ * Extracts a cell's plain-text value. Formula cells use their cached result (`v`); date
+ * serials (a numeric value with a date number format) are rendered as ISO 8601.
+ */
+function cellText(cell: ICellData | undefined, styles: Record<string, IStyleData | null>): string {
if (!cell || cell.v == null) return "";
if (typeof cell.v === "boolean") return cell.v ? "TRUE" : "FALSE";
+
+ const pattern = resolveCellStyle(cell.s, styles)?.n?.pattern;
+ if (pattern && isFiniteNumber(cell.v) && isDateFormat(pattern)) {
+ const formatted = formatDate(pattern, cell.v);
+ if (formatted != null) return formatted;
+ }
+
return String(cell.v);
}
+/**
+ * Renders a date serial as ISO 8601 when the format is a full year-month-day date (with
+ * time appended only if the format carries it). Partial date formats (e.g. month-year only)
+ * fall back to the cell's own pattern so the output stays a readable date, never a serial.
+ * Returns `null` if the value can't be formatted, so the caller falls back to the raw value.
+ */
+function formatDate(pattern: string, serial: number): string | null {
+ try {
+ const info = getFormatDateInfo(pattern);
+ if (info.year && info.month && info.day) {
+ let isoFormat = "yyyy-mm-dd";
+ if (info.seconds) isoFormat += " hh:mm:ss";
+ else if (info.hours || info.minutes) isoFormat += " hh:mm";
+ return formatNumfmt(isoFormat, serial);
+ }
+ return formatNumfmt(pattern, serial);
+ } catch {
+ return null;
+ }
+}
+
/**
* Quotes a field per RFC 4180 when it contains a comma, double quote, CR, or LF;
* embedded double quotes are doubled. Plain fields pass through unchanged.
diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.ts
index 179edd204f..c9523238eb 100644
--- a/packages/commons/src/lib/spreadsheet/workbook_model.ts
+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts
@@ -114,6 +114,16 @@ export interface IColumnData {
hd?: number;
}
+// Univer's cell value type (`ICellData.t`). Tells the editor how to render/sort a value
+// independently of the JS type of `v` (e.g. FORCE_STRING keeps a numeric-looking string
+// left-aligned and un-coerced).
+export const enum CellValueType {
+ STRING = 1,
+ NUMBER = 2,
+ BOOLEAN = 3,
+ FORCE_STRING = 4
+}
+
// Alignment enums (from UniversJS).
export const enum HorizontalAlign {
LEFT = 1,