Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(spreadsheet): basic export to CSV
Elian Doranb05ce377ac9c
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 23bf57aa52..ffe5a26500 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -493,6 +493,7 @@ type EventMappings = {exportSvg: { ntxId: string | null | undefined; };exportPng: { ntxId: string | null | undefined; };exportXlsx: { ntxId: string | null | undefined; };+ exportCsv: { ntxId: string | null | undefined; };geoMapCreateChildNote: {ntxId: string | null | undefined; // TODO: deduplicate ntxId};diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 9211978e41..2a69541e4e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2740,7 +2740,9 @@"spreadsheet": {"read-only": "This note is read-only.","export-xlsx": "Export to Excel (.xlsx)",- "export-failed": "Failed to export the spreadsheet to Excel."+ "export-csv": "Export to CSV (.csv)",+ "export-failed": "Failed to export the spreadsheet to Excel.",+ "export-csv-failed": "Failed to export the spreadsheet to CSV."},"text-editor": {"checkbox-tooltip": "Right click for more task states.\nPress {{shortcut}} to cycle between states.",diff --git a/apps/client/src/widgets/FloatingButtonsDefinitions.tsx b/apps/client/src/widgets/FloatingButtonsDefinitions.tsxindex 419f51db4a..c21de3c166 100644--- a/apps/client/src/widgets/FloatingButtonsDefinitions.tsx+++ b/apps/client/src/widgets/FloatingButtonsDefinitions.tsx@@ -332,11 +332,18 @@ function ExportImageButtons({ note, triggerEvent, isDefaultViewMode }: FloatingBfunction ExportSpreadsheetButton({ note, triggerEvent, isDefaultViewMode }: FloatingButtonContext) {const isEnabled = note?.type === "spreadsheet" && note?.isContentAvailable() && isDefaultViewMode;return isEnabled && (- <FloatingButton- icon="bx bxs-spreadsheet"- text={t("spreadsheet.export-xlsx")}- onClick={() => triggerEvent("exportXlsx")}- />+ <>+ <FloatingButton+ icon="bx bxs-spreadsheet"+ text={t("spreadsheet.export-xlsx")}+ onClick={() => triggerEvent("exportXlsx")}+ />+ <FloatingButton+ icon="bx bxs-spreadsheet"+ text={t("spreadsheet.export-csv")}+ onClick={() => triggerEvent("exportCsv")}+ />+ </>);}diff --git a/apps/client/src/widgets/ribbon/NoteActions.tsx b/apps/client/src/widgets/ribbon/NoteActions.tsxindex f950bb0d9c..fcf8b4d193 100644--- a/apps/client/src/widgets/ribbon/NoteActions.tsx+++ b/apps/client/src/widgets/ribbon/NoteActions.tsx@@ -153,10 +153,16 @@ export function NoteContextMenu({ note, noteContext, itemsAtStart, itemsNearNote})} />{isExportableToImage && isNormalViewMode && isContentAvailable && <ExportAsImage ntxId={noteContext.ntxId} parentComponent={parentComponent} />}{isExportableToXlsx && isNormalViewMode && isContentAvailable && (- <FormListItem- icon="bx bxs-spreadsheet"- onClick={() => parentComponent?.triggerEvent("exportXlsx", { ntxId: noteContext.ntxId })}- >{t("spreadsheet.export-xlsx")}</FormListItem>+ <>+ <FormListItem+ icon="bx bxs-spreadsheet"+ onClick={() => parentComponent?.triggerEvent("exportXlsx", { ntxId: noteContext.ntxId })}+ >{t("spreadsheet.export-xlsx")}</FormListItem>+ <FormListItem+ icon="bx bxs-spreadsheet"+ onClick={() => parentComponent?.triggerEvent("exportCsv", { ntxId: noteContext.ntxId })}+ >{t("spreadsheet.export-csv")}</FormListItem>+ </>)}<CommandItem command="printActiveNote" icon="bx bx-printer" disabled={!isPrintable}text={isElectron ? t("note_actions.print_or_export_to_pdf") : t("note_actions.print_note")}diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/export.tsxindex b323ceabae..aeeef41f1a 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx+++ b/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx@@ -9,47 +9,78 @@ import utils from "../../../services/utils";import { useTriliumEvent } from "../../react/hooks";const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";+const CSV_MIME = "text/csv;charset=utf-8";+// Excel on Windows only auto-detects UTF-8 in a CSV when it starts with a byte-order mark.+const UTF8_BOM = "\uFEFF";/**- * Exports the spreadsheet to an `.xlsx` file when the `exportXlsx` event fires for this note- * context. The event is raised from the note actions menu and the floating buttons (the same- * surfaces the PNG/SVG exports use), so it works regardless of Univer's own toolbar (which is- * hidden in read-only mode). The conversion runs client-side via the `exceljs`-backed exporter- * in `@triliumnext/commons`, dynamically imported so exceljs is only fetched on export (and- * never enters the standalone/core bundles).+ * Exports the spreadsheet when the `exportXlsx` / `exportCsv` events fire for this note+ * context. The events are raised from the note actions menu and the floating buttons (the+ * same surfaces the PNG/SVG exports use), so they work regardless of Univer's own toolbar+ * (which is hidden in read-only mode). The conversions run client-side via the exporters in+ * `@triliumnext/commons`, dynamically imported so their dependencies (e.g. exceljs) are only+ * fetched on export (and never enter the standalone/core bundles).*/export default function useSpreadsheetExport(apiRef: MutableRef<FUniver | undefined>, note: FNote, noteContext: NoteContext | null | undefined) {useTriliumEvent("exportXlsx", ({ ntxId }) => {if (ntxId !== noteContext?.ntxId) return;void exportToXlsx(apiRef.current, note);});+ useTriliumEvent("exportCsv", ({ ntxId }) => {+ if (ntxId !== noteContext?.ntxId) return;+ void exportToCsv(apiRef.current, note);+ });}async function exportToXlsx(univerAPI: FUniver | undefined, note: FNote) {- if (!univerAPI) return;+ const json = serializeWorkbook(univerAPI);+ if (json == null) return;try {- const workbook = univerAPI.getActiveWorkbook();- if (!workbook) return;-- // Serialize the live workbook in the same shape the note is persisted in.- const json = JSON.stringify({ version: 1, workbook: workbook.save() });-// Dynamic import keeps exceljs out of the main bundle (and out of standalone/core).const { renderSpreadsheetToXlsx } = await import("@triliumnext/commons/src/lib/spreadsheet/render_to_xlsx");const buffer = await renderSpreadsheetToXlsx(json);-- // Download via a data URL (utils.triggerDownload): a blob-URL anchor click after these- // awaits gets silently blocked once the user-activation is consumed, whereas the- // data-URL path used by downloadAsPng/Svg works.- const dataUrl = await blobToDataUrl(new Blob([buffer as BlobPart], { type: XLSX_MIME }));- utils.triggerDownload(`${note.title || "spreadsheet"}.xlsx`, dataUrl);+ await download(note, "xlsx", new Blob([buffer as BlobPart], { type: XLSX_MIME }));} catch (e) {- console.error("[spreadsheet-export] failed", e);+ console.error("[spreadsheet-export] xlsx failed", e);toast.showError(t("spreadsheet.export-failed"));}}+async function exportToCsv(univerAPI: FUniver | undefined, note: FNote) {+ if (!univerAPI) return;++ const json = serializeWorkbook(univerAPI);+ if (json == null) return;++ try {+ // CSV holds a single sheet, so export the one the user is looking at.+ const sheetId = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getSheetId();++ const { renderSpreadsheetToCsv } = await import("@triliumnext/commons/src/lib/spreadsheet/render_to_csv");+ const csv = renderSpreadsheetToCsv(json, { sheetId });+ await download(note, "csv", new Blob([UTF8_BOM + csv], { type: CSV_MIME }));+ } catch (e) {+ console.error("[spreadsheet-export] csv failed", e);+ toast.showError(t("spreadsheet.export-csv-failed"));+ }+}++/** Serializes the live workbook in the same shape the note is persisted in. */+function serializeWorkbook(univerAPI: FUniver | undefined): string | null {+ const workbook = univerAPI?.getActiveWorkbook();+ if (!workbook) return null;+ return JSON.stringify({ version: 1, workbook: workbook.save() });+}++async function download(note: FNote, extension: string, blob: Blob) {+ // Download via a data URL (utils.triggerDownload): a blob-URL anchor click after these+ // awaits gets silently blocked once the user-activation is consumed, whereas the+ // data-URL path used by downloadAsPng/Svg works.+ const dataUrl = await blobToDataUrl(blob);+ utils.triggerDownload(`${note.title || "spreadsheet"}.${extension}`, dataUrl);+}+function blobToDataUrl(blob: Blob): Promise<string> {return new Promise((resolve, reject) => {const reader = new FileReader();diff --git a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.tsnew file mode 100644index 0000000000..da00520d44--- /dev/null+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts@@ -0,0 +1,128 @@+import { describe, expect, it } from "vitest";++import { renderSpreadsheetToCsv } from "./render_to_csv.js";++/** Build a workbook payload from a sparse cell matrix (keyed by row, then column). */+function workbook(+ cellData: Record<number, Record<number, unknown>>,+ sheetExtra: Record<string, unknown> = {},+ workbookExtra: Record<string, unknown> = {}+): string {+ return JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1"],+ styles: {},+ sheets: {+ s1: {+ id: "s1",+ name: "Sheet1",+ hidden: 0,+ mergeData: [],+ cellData,+ rowData: {},+ columnData: {},+ ...sheetExtra+ }+ },+ ...workbookExtra+ }+ });+}++describe("renderSpreadsheetToCsv", () => {+ it("lays cells out as a dense rectangle, filling gaps with empty fields", () => {+ const csv = renderSpreadsheetToCsv(workbook({+ 0: { 0: { v: "a" }, 2: { v: "c" } },+ 1: { 1: { v: "b" } }+ }));+ // Bounds span rows 0-1, cols 0-2; missing cells become empty fields.+ expect(csv).toBe("a,,c\r\n,b,");+ });++ it("offsets the grid to the populated bounds (no leading empty rows/cols)", () => {+ const csv = renderSpreadsheetToCsv(workbook({+ 2: { 3: { v: "x" }, 4: { v: "y" } }+ }));+ expect(csv).toBe("x,y");+ });++ it("renders numbers and booleans as raw values", () => {+ const csv = renderSpreadsheetToCsv(workbook({+ 0: { 0: { v: 42, t: 2 }, 1: { v: true, t: 3 }, 2: { v: false, t: 3 } }+ }));+ expect(csv).toBe("42,TRUE,FALSE");+ });++ it("exports a formula cell's cached result, not the formula", () => {+ const csv = renderSpreadsheetToCsv(workbook({+ 0: { 0: { f: "=1+2", v: 3 } }+ }));+ expect(csv).toBe("3");+ });++ 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" } }+ }));+ expect(csv).toBe('"a,b","he said ""hi""","line1\nline2"');+ });++ it("treats empty and null cell values as empty fields", () => {+ const csv = renderSpreadsheetToCsv(workbook({+ 0: { 0: { v: "" }, 1: { v: null }, 2: { v: "z" } }+ }));+ expect(csv).toBe(",,z");+ });++ it("exports the first visible sheet by default and the requested sheet by id", () => {+ const json = JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1", "s2"],+ styles: {},+ sheets: {+ s1: { id: "s1", name: "First", hidden: 0, cellData: { 0: { 0: { v: "one" } } } },+ s2: { id: "s2", name: "Second", hidden: 0, cellData: { 0: { 0: { v: "two" } } } }+ }+ }+ });+ expect(renderSpreadsheetToCsv(json)).toBe("one");+ expect(renderSpreadsheetToCsv(json, { sheetId: "s2" })).toBe("two");+ // Unknown id falls back to the first visible sheet.+ expect(renderSpreadsheetToCsv(json, { sheetId: "nope" })).toBe("one");+ });++ it("skips hidden sheets when choosing the default", () => {+ const json = JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1", "s2"],+ styles: {},+ sheets: {+ s1: { id: "s1", name: "Hidden", hidden: 1, cellData: { 0: { 0: { v: "hidden" } } } },+ s2: { id: "s2", name: "Visible", hidden: 0, cellData: { 0: { 0: { v: "visible" } } } }+ }+ }+ });+ expect(renderSpreadsheetToCsv(json)).toBe("visible");+ });++ it("returns an empty string for an empty sheet or a workbook with no visible sheets", () => {+ expect(renderSpreadsheetToCsv(workbook({}))).toBe("");++ const allHidden = JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1"],+ sheets: { s1: { id: "s1", name: "H", hidden: 1, cellData: {} } }+ }+ });+ expect(renderSpreadsheetToCsv(allHidden)).toBe("");+ });++ it("throws on unparseable JSON and on a workbook with no sheets", () => {+ expect(() => renderSpreadsheetToCsv("not json")).toThrow(/parse/i);+ expect(() => renderSpreadsheetToCsv(JSON.stringify({ version: 1 }))).toThrow(/no sheets/i);+ });+});diff --git a/packages/commons/src/lib/spreadsheet/render_to_csv.ts b/packages/commons/src/lib/spreadsheet/render_to_csv.tsnew file mode 100644index 0000000000..457af3879a--- /dev/null+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.ts@@ -0,0 +1,98 @@+/**+ * Converts a UniversJS workbook JSON structure into a CSV file (RFC 4180).+ *+ * 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.+ *+ * 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 {+ computeBounds,+ getVisibleSheets,+ type ICellData,+ type IWorksheetData,+ parseWorkbookData+} from "./workbook_model.js";++export interface CsvRenderOptions {+ /** Id of the sheet to export. Falls back to the first visible sheet when omitted or not found. */+ sheetId?: string;+}++/**+ * Parses the raw JSON content of a spreadsheet note and renders a single sheet as CSV.+ * Hidden rows and columns are still exported (their data is part of the sheet). Returns+ * an empty string for an empty sheet. Throws if the content is not a parseable workbook.+ */+export function renderSpreadsheetToCsv(jsonContent: string, options: CsvRenderOptions = {}): string {+ const { ok, data } = parseWorkbookData(jsonContent);+ if (!ok) {+ throw new Error("Unable to parse spreadsheet data.");+ }++ if (!data?.workbook?.sheets) {+ throw new Error("Spreadsheet contains no sheets.");+ }++ const visibleSheets = getVisibleSheets(data.workbook);+ if (visibleSheets.length === 0) {+ return "";+ }++ const sheet = pickSheet(visibleSheets, options.sheetId);+ return renderSheet(sheet);+}++function pickSheet(visibleSheets: IWorksheetData[], sheetId: string | undefined): IWorksheetData {+ if (sheetId) {+ const match = visibleSheets.find((s) => s.id === sheetId);+ if (match) return match;+ }+ return visibleSheets[0];+}++function renderSheet(sheet: IWorksheetData): string {+ const { cellData } = sheet;+ const bounds = computeBounds(cellData, sheet.mergeData);+ if (!bounds) {+ return "";+ }++ const { minRow, maxRow, minCol, maxCol } = bounds;+ const lines: 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])));+ }+ lines.push(cells.join(","));+ }++ // RFC 4180 uses CRLF as the record separator.+ 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 {+ if (!cell || cell.v == null) return "";+ if (typeof cell.v === "boolean") return cell.v ? "TRUE" : "FALSE";+ return String(cell.v);+}++/**+ * 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.+ */+function escapeCsvField(value: string): string {+ if (/[",\r\n]/.test(value)) {+ return `"${value.replace(/"/g, '""')}"`;+ }+ return value;+}diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex 57d8340835..25fd465e4b 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -12,141 +12,29 @@import { format as formatNumfmt, formatColor as formatNumfmtColor } from "numfmt";-// #region UniversJS type subset--interface PersistedData {- version: number;- workbook: IWorkbookData;-}--interface IWorkbookData {- sheetOrder: string[];- styles?: Record<string, IStyleData | null>;- sheets: Record<string, IWorksheetData>;-}--interface IWorksheetData {- id: string;- name: string;- hidden?: number;- rowCount: number;- columnCount: number;- defaultColumnWidth?: number;- defaultRowHeight?: number;- mergeData?: IRange[];- cellData: CellMatrix;- rowData?: Record<number, IRowData>;- columnData?: Record<number, IColumnData>;- showGridlines?: number;- gridlinesColor?: string | null;-}--type CellMatrix = Record<number, Record<number, ICellData>>;--interface ICellData {- v?: string | number | boolean | null;- t?: number | null;- s?: IStyleData | string | null;-}--interface IStyleData {- bl?: number;- it?: number;- ul?: ITextDecoration;- st?: ITextDecoration;- fs?: number;- ff?: string | null;- bg?: IColorStyle | null;- cl?: IColorStyle | null;- ht?: number | null;- vt?: number | null;- bd?: IBorderData | null;- n?: INumberFormat | null;-}--interface INumberFormat {- pattern?: string | null;-}--interface ITextDecoration {- s?: number;-}--interface IColorStyle {- rgb?: string | null;-}--interface IBorderData {- t?: IBorderStyleData | null;- r?: IBorderStyleData | null;- b?: IBorderStyleData | null;- l?: IBorderStyleData | null;-}--interface IBorderStyleData {- s?: number;- cl?: IColorStyle;-}--interface IRange {- startRow: number;- endRow: number;- startColumn: number;- endColumn: number;-}--interface IRowData {- h?: number;- hd?: number;-}--interface IColumnData {- w?: number;- hd?: number;-}--// Alignment enums (from UniversJS)-const enum HorizontalAlign {- LEFT = 1,- CENTER = 2,- RIGHT = 3-}--const enum VerticalAlign {- TOP = 1,- MIDDLE = 2,- BOTTOM = 3-}--// Border style enum — mirrors Univer's `BorderStyleTypes` (@univerjs/core).-const enum BorderStyle {- NONE = 0,- THIN = 1,- HAIR = 2,- DOTTED = 3,- DASHED = 4,- DASH_DOT = 5,- DASH_DOT_DOT = 6,- DOUBLE = 7,- MEDIUM = 8,- MEDIUM_DASHED = 9,- MEDIUM_DASH_DOT = 10,- MEDIUM_DASH_DOT_DOT = 11,- SLANT_DASH_DOT = 12,- THICK = 13-}--// #endregion+import {+ BorderStyle,+ computeBounds,+ getVisibleSheets,+ HorizontalAlign,+ type IBorderStyleData,+ type ICellData,+ isFiniteNumber,+ type IRange,+ type IStyleData,+ type IWorksheetData,+ parseWorkbookData,+ resolveCellStyle,+ VerticalAlign+} from "./workbook_model.js";/*** Parses the raw JSON content of a spreadsheet note and renders it as HTML.* Returns an HTML string containing one `<table>` per visible sheet.*/export function renderSpreadsheetToHtml(jsonContent: string): string {- let data: PersistedData;- try {- data = JSON.parse(jsonContent);- } catch {+ const { ok, data } = parseWorkbookData(jsonContent);+ if (!ok) {return "<p>Unable to parse spreadsheet data.</p>";}@@ -155,10 +43,7 @@ export function renderSpreadsheetToHtml(jsonContent: string): string {}const { workbook } = data;- const sheetIds = workbook.sheetOrder ?? Object.keys(workbook.sheets);- const visibleSheets = sheetIds- .map((id) => workbook.sheets[id])- .filter((s) => s && !s.hidden);+ const visibleSheets = getVisibleSheets(workbook);if (visibleSheets.length === 0) {return "<p>Empty spreadsheet.</p>";@@ -219,7 +104,7 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |if (mergeInfo === "hidden") continue;const cell = cellData[row]?.[col];- const cellStyle = resolveCellStyle(cell, styles);+ const cellStyle = resolveCellStyle(cell?.s, styles);const cssText = buildCssText(cellStyle, cell);const value = formatCellValue(cell, cellStyle);@@ -264,47 +149,6 @@ function buildTableTag(sheet: IWorksheetData): string {return `<table class="spreadsheet-table show-gridlines"${style}>`;}-// #region Bounds computation--interface Bounds {- minRow: number;- maxRow: number;- minCol: number;- maxCol: number;-}--function computeBounds(cellData: CellMatrix, mergeData: IRange[]): Bounds | null {- let minRow = Infinity;- let maxRow = -Infinity;- let minCol = Infinity;- let maxCol = -Infinity;-- for (const rowStr of Object.keys(cellData)) {- const row = Number(rowStr);- const cols = cellData[row];- for (const colStr of Object.keys(cols)) {- const col = Number(colStr);- if (minRow > row) minRow = row;- if (maxRow < row) maxRow = row;- if (minCol > col) minCol = col;- if (maxCol < col) maxCol = col;- }- }-- // Extend bounds to cover merged ranges.- for (const range of mergeData) {- if (minRow > range.startRow) minRow = range.startRow;- if (maxRow < range.endRow) maxRow = range.endRow;- if (minCol > range.startColumn) minCol = range.startColumn;- if (maxCol < range.endColumn) maxCol = range.endColumn;- }-- if (minRow > maxRow) return null;- return { minRow, maxRow, minCol, maxCol };-}--// #endregion-// #region Merge handlinginterface MergeOrigin {@@ -347,16 +191,6 @@ function buildMergeMap(mergeData: IRange[], minRow: number, maxRow: number, minC// #region Style resolution-function resolveCellStyle(cell: ICellData | undefined, styles: Record<string, IStyleData | null>): IStyleData | null {- if (!cell?.s) return null;-- if (typeof cell.s === "string") {- return styles[cell.s] ?? null;- }-- return cell.s;-}-function buildCssText(style: IStyleData | null, cell?: ICellData): string {if (!style) return "";@@ -464,11 +298,6 @@ function borderStyleToCss(style: number | undefined): string {}}-/** Checks that a value is a finite number (guards against stringified payloads from JSON). */-function isFiniteNumber(v: unknown): v is number {- return typeof v === "number" && Number.isFinite(v);-}-/*** Sanitizes an arbitrary string for use as a CSS value by removing characters* that could break out of a property (semicolons, braces, angle brackets, etc.).diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.tsindex adcb7227d1..66bf946c4a 100644--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts@@ -6,144 +6,26 @@* Excel's, and fonts/fills/alignment/merges map directly. The heavy lifting (zip + XML) is* delegated to `exceljs`.*- * DRAFT: the workbook-reading type subset and the `BorderStyle` enum are duplicated from- * `render_to_html.ts` for now. Once a second consumer lands, lift the shared reader (parse,- * sheet selection, style resolution, the type subset) into its own module and have both the- * HTML and XLSX emitters depend on it.+ * The workbook type subset, sheet selection, and style resolution live in the shared+ * `workbook_model` reader; this module only owns the Univer→OOXML translation.*/import ExcelJS from "exceljs";-// #region UniversJS type subset--interface PersistedData {- version: number;- workbook: IWorkbookData;-}--interface IWorkbookData {- sheetOrder: string[];- name?: string;- styles?: Record<string, IStyleData | null>;- sheets: Record<string, IWorksheetData>;-}--interface IWorksheetData {- id: string;- name: string;- hidden?: number;- defaultColumnWidth?: number;- defaultRowHeight?: number;- mergeData?: IRange[];- cellData: CellMatrix;- rowData?: Record<number, IRowData>;- columnData?: Record<number, IColumnData>;- showGridlines?: number;-}--type CellMatrix = Record<number, Record<number, ICellData>>;--interface ICellData {- v?: string | number | boolean | null;- t?: number | null;- s?: IStyleData | string | null;- f?: string | null;-}--interface IStyleData {- bl?: number;- it?: number;- ul?: ITextDecoration;- st?: ITextDecoration;- fs?: number;- ff?: string | null;- bg?: IColorStyle | null;- cl?: IColorStyle | null;- ht?: number | null;- vt?: number | null;- tb?: number | null;- tr?: ITextRotation | null;- bd?: IBorderData | null;- n?: { pattern?: string | null } | null;-}--interface ITextDecoration {- s?: number;-}--interface IColorStyle {- rgb?: string | null;-}--interface ITextRotation {- a?: number;- v?: number;-}--interface IBorderData {- t?: IBorderStyleData | null;- r?: IBorderStyleData | null;- b?: IBorderStyleData | null;- l?: IBorderStyleData | null;-}--interface IBorderStyleData {- s?: number;- cl?: IColorStyle;-}--interface IRange {- startRow: number;- endRow: number;- startColumn: number;- endColumn: number;-}--interface IRowData {- h?: number;- hd?: number;-}--interface IColumnData {- w?: number;- hd?: number;-}--const enum HorizontalAlign {- LEFT = 1,- CENTER = 2,- RIGHT = 3-}--const enum VerticalAlign {- TOP = 1,- MIDDLE = 2,- BOTTOM = 3-}--const enum WrapStrategy {- WRAP = 3-}--// Univer BorderStyleTypes (@univerjs/core) -> exceljs border styles (OOXML names).-const enum BorderStyle {- NONE = 0,- THIN = 1,- HAIR = 2,- DOTTED = 3,- DASHED = 4,- DASH_DOT = 5,- DASH_DOT_DOT = 6,- DOUBLE = 7,- MEDIUM = 8,- MEDIUM_DASHED = 9,- MEDIUM_DASH_DOT = 10,- MEDIUM_DASH_DOT_DOT = 11,- SLANT_DASH_DOT = 12,- THICK = 13-}--// #endregion+import {+ BorderStyle,+ getVisibleSheets,+ HorizontalAlign,+ type IBorderData,+ type ICellData,+ isFiniteNumber,+ type IStyleData,+ type IWorksheetData,+ parseWorkbookData,+ resolveCellStyle,+ VerticalAlign,+ WrapStrategy+} from "./workbook_model.js";/*** Parses the raw JSON content of a spreadsheet note and produces an `.xlsx` workbook as a@@ -151,10 +33,8 @@ const enum BorderStyle {* hidden (Excel keeps the data). Throws if the content is not a parseable workbook.*/export async function renderSpreadsheetToXlsx(jsonContent: string): Promise<ExcelJS.Buffer> {- let data: PersistedData;- try {- data = JSON.parse(jsonContent);- } catch {+ const { ok, data } = parseWorkbookData(jsonContent);+ if (!ok) {throw new Error("Unable to parse spreadsheet data.");}@@ -166,10 +46,7 @@ export async function renderSpreadsheetToXlsx(jsonContent: string): Promise<Exceconst styles = workbook.styles ?? {};const out = new ExcelJS.Workbook();- const sheetIds = workbook.sheetOrder ?? Object.keys(workbook.sheets);- const visibleSheets = sheetIds- .map((id) => workbook.sheets[id])- .filter((s) => s && !s.hidden);+ const visibleSheets = getVisibleSheets(workbook);// Always emit at least one sheet so the file is a valid workbook.if (visibleSheets.length === 0) {@@ -237,7 +114,7 @@ function writeCell(target: ExcelJS.Cell, cell: ICellData | undefined, styles: ResetCellValue(target, cell);- const style = resolveStyle(cell.s, styles);+ const style = resolveCellStyle(cell.s, styles);if (!style) return;if (style.n?.pattern) target.numFmt = style.n.pattern;@@ -266,12 +143,6 @@ function setCellValue(target: ExcelJS.Cell, cell: ICellData): void {target.value = cell.v;}-function resolveStyle(s: ICellData["s"], styles: Record<string, IStyleData | null>): IStyleData | null {- if (!s) return null;- if (typeof s === "string") return styles[s] ?? null;- return s;-}-function buildFont(style: IStyleData): Partial<ExcelJS.Font> | null {const font: Partial<ExcelJS.Font> = {};let any = false;@@ -387,7 +258,3 @@ function pxToExcelWidth(px: number): number {function pxToPoints(px: number): number {return px * 0.75;}--function isFiniteNumber(v: unknown): v is number {- return typeof v === "number" && Number.isFinite(v);-}diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.tsnew file mode 100644index 0000000000..179edd204f--- /dev/null+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts@@ -0,0 +1,242 @@+/**+ * Shared reader for UniversJS workbook JSON, used by the spreadsheet emitters+ * (`render_to_html`, `render_to_xlsx`, `render_to_csv`).+ *+ * Only the subset of UniversJS types needed for rendering is defined here, to avoid+ * depending on `@univerjs/core`. This is intentionally a superset of every emitter's+ * needs: HTML uses gridlines/number-format colors, XLSX uses formulas/wrap/rotation,+ * CSV uses just values and bounds — they all share one model.+ *+ * Parsing is deliberately lenient (`parseWorkbookData` returns `null` on failure)+ * because each emitter reports errors differently: HTML returns placeholder markup,+ * XLSX throws. The shared layer hands back the parsed data and lets the caller decide.+ */++// #region UniversJS type subset++export interface PersistedData {+ version: number;+ workbook: IWorkbookData;+}++export interface IWorkbookData {+ sheetOrder: string[];+ name?: string;+ styles?: Record<string, IStyleData | null>;+ sheets: Record<string, IWorksheetData>;+}++export interface IWorksheetData {+ id: string;+ name: string;+ hidden?: number;+ rowCount?: number;+ columnCount?: number;+ defaultColumnWidth?: number;+ defaultRowHeight?: number;+ mergeData?: IRange[];+ cellData: CellMatrix;+ rowData?: Record<number, IRowData>;+ columnData?: Record<number, IColumnData>;+ showGridlines?: number;+ gridlinesColor?: string | null;+}++export type CellMatrix = Record<number, Record<number, ICellData>>;++export interface ICellData {+ v?: string | number | boolean | null;+ t?: number | null;+ s?: IStyleData | string | null;+ f?: string | null;+}++export interface IStyleData {+ bl?: number;+ it?: number;+ ul?: ITextDecoration;+ st?: ITextDecoration;+ fs?: number;+ ff?: string | null;+ bg?: IColorStyle | null;+ cl?: IColorStyle | null;+ ht?: number | null;+ vt?: number | null;+ tb?: number | null;+ tr?: ITextRotation | null;+ bd?: IBorderData | null;+ n?: INumberFormat | null;+}++export interface INumberFormat {+ pattern?: string | null;+}++export interface ITextDecoration {+ s?: number;+}++export interface IColorStyle {+ rgb?: string | null;+}++export interface ITextRotation {+ a?: number;+ v?: number;+}++export interface IBorderData {+ t?: IBorderStyleData | null;+ r?: IBorderStyleData | null;+ b?: IBorderStyleData | null;+ l?: IBorderStyleData | null;+}++export interface IBorderStyleData {+ s?: number;+ cl?: IColorStyle;+}++export interface IRange {+ startRow: number;+ endRow: number;+ startColumn: number;+ endColumn: number;+}++export interface IRowData {+ h?: number;+ hd?: number;+}++export interface IColumnData {+ w?: number;+ hd?: number;+}++// Alignment enums (from UniversJS).+export const enum HorizontalAlign {+ LEFT = 1,+ CENTER = 2,+ RIGHT = 3+}++export const enum VerticalAlign {+ TOP = 1,+ MIDDLE = 2,+ BOTTOM = 3+}++export const enum WrapStrategy {+ WRAP = 3+}++// Border style enum — mirrors Univer's `BorderStyleTypes` (@univerjs/core).+export const enum BorderStyle {+ NONE = 0,+ THIN = 1,+ HAIR = 2,+ DOTTED = 3,+ DASHED = 4,+ DASH_DOT = 5,+ DASH_DOT_DOT = 6,+ DOUBLE = 7,+ MEDIUM = 8,+ MEDIUM_DASHED = 9,+ MEDIUM_DASH_DOT = 10,+ MEDIUM_DASH_DOT_DOT = 11,+ SLANT_DASH_DOT = 12,+ THICK = 13+}++// #endregion++export interface WorkbookParseResult {+ /** `false` only when the content is not valid JSON (vs. valid JSON that lacks a workbook). */+ ok: boolean;+ data: PersistedData | null;+}++/**+ * Parses the raw JSON content of a spreadsheet note. `ok` is `false` only when the content+ * is not valid JSON; valid-but-empty JSON (e.g. `null`, `{}`) returns `ok: true` with the+ * parsed value, so callers can distinguish an unparseable payload from a structurally empty+ * one. Callers should additionally check `data.workbook?.sheets` and report an empty/invalid+ * workbook in their own format.+ */+export function parseWorkbookData(jsonContent: string): WorkbookParseResult {+ try {+ return { ok: true, data: JSON.parse(jsonContent) };+ } catch {+ return { ok: false, data: null };+ }+}++/**+ * Returns the sheets to render, in `sheetOrder`, skipping hidden ones. Falls back to+ * `Object.keys` order when `sheetOrder` is absent.+ */+export function getVisibleSheets(workbook: IWorkbookData): IWorksheetData[] {+ const sheetIds = workbook.sheetOrder ?? Object.keys(workbook.sheets);+ return sheetIds+ .map((id) => workbook.sheets[id])+ .filter((s): s is IWorksheetData => Boolean(s) && !s.hidden);+}++/**+ * Resolves a cell's style reference to a concrete style object. Univer stores a cell's+ * style either inline (an object) or as a key into the workbook's shared `styles` table.+ */+export function resolveCellStyle(+ s: ICellData["s"],+ styles: Record<string, IStyleData | null>+): IStyleData | null {+ if (!s) return null;+ if (typeof s === "string") return styles[s] ?? null;+ return s;+}++export interface Bounds {+ minRow: number;+ maxRow: number;+ minCol: number;+ maxCol: number;+}++/**+ * Computes the inclusive bounding rectangle of all populated cells, extended to cover+ * any merged ranges. Returns `null` when there are no cells and no merges (empty sheet).+ */+export function computeBounds(cellData: CellMatrix, mergeData: IRange[] = []): Bounds | null {+ let minRow = Infinity;+ let maxRow = -Infinity;+ let minCol = Infinity;+ let maxCol = -Infinity;++ for (const rowStr of Object.keys(cellData)) {+ const row = Number(rowStr);+ const cols = cellData[row];+ for (const colStr of Object.keys(cols)) {+ const col = Number(colStr);+ if (minRow > row) minRow = row;+ if (maxRow < row) maxRow = row;+ if (minCol > col) minCol = col;+ if (maxCol < col) maxCol = col;+ }+ }++ for (const range of mergeData) {+ if (minRow > range.startRow) minRow = range.startRow;+ if (maxRow < range.endRow) maxRow = range.endRow;+ if (minCol > range.startColumn) minCol = range.startColumn;+ if (maxCol < range.endColumn) maxCol = range.endColumn;+ }++ if (minRow > maxRow) return null;+ return { minRow, maxRow, minCol, maxCol };+}++/** Checks that a value is a finite number (guards against stringified payloads from JSON). */+export function isFiniteNumber(v: unknown): v is number {+ return typeof v === "number" && Number.isFinite(v);+}