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(export/spreadsheet): multi-sheet CSV export
Elian Doran93482d7910c8
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/export.tsxindex aeeef41f1a..0d26c45994 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx+++ b/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx@@ -10,6 +10,7 @@ import { useTriliumEvent } from "../../react/hooks";const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";const CSV_MIME = "text/csv;charset=utf-8";+const ZIP_MIME = "application/zip";// Excel on Windows only auto-detects UTF-8 in a CSV when it starts with a byte-order mark.const UTF8_BOM = "\uFEFF";@@ -48,15 +49,23 @@ async function exportToXlsx(univerAPI: FUniver | undefined, note: FNote) {}async function exportToCsv(univerAPI: FUniver | undefined, note: FNote) {- if (!univerAPI) return;+ const workbook = univerAPI?.getActiveWorkbook();+ if (!workbook) return;- const json = serializeWorkbook(univerAPI);- if (json == null) return;+ const wbData = workbook.save();+ const json = JSON.stringify({ version: 1, workbook: wbData });try {- // CSV holds a single sheet, so export the one the user is looking at.- const sheetId = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getSheetId();+ // A workbook with multiple visible sheets can't fit in one CSV, so bundle one file per+ // sheet into a zip; a single-sheet workbook downloads as a plain .csv of that sheet.+ if (countVisibleSheets(wbData) > 1) {+ const { renderSpreadsheetToCsvZip } = await import("@triliumnext/commons/src/lib/spreadsheet/render_to_csv");+ const zip = await renderSpreadsheetToCsvZip(json);+ await download(note, "zip", new Blob([zip as BlobPart], { type: ZIP_MIME }));+ return;+ }+ const sheetId = workbook.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 }));@@ -66,6 +75,13 @@ async function exportToCsv(univerAPI: FUniver | undefined, note: FNote) {}}+/** Counts the sheets Univer's `save()` reports as not hidden — mirrors `getVisibleSheets` in commons. */+function countVisibleSheets(wbData: { sheetOrder?: string[]; sheets?: Record<string, { hidden?: number }> }): number {+ const sheets = wbData.sheets ?? {};+ const ids = wbData.sheetOrder ?? Object.keys(sheets);+ return ids.filter((id) => sheets[id] && !sheets[id].hidden).length;+}+/** Serializes the live workbook in the same shape the note is persisted in. */function serializeWorkbook(univerAPI: FUniver | undefined): string | null {const workbook = univerAPI?.getActiveWorkbook();diff --git a/packages/commons/package.json b/packages/commons/package.jsonindex 481f6b3cc1..fe6fdc3585 100644--- a/packages/commons/package.json+++ b/packages/commons/package.json@@ -17,6 +17,7 @@"dependencies": {"dayjs": "1.11.21","exceljs": "4.4.0",+ "jszip": "3.10.1","marked": "18.0.4","marked-footnote": "1.4.0","numfmt": "3.2.6"diff --git a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.tsindex 22ec9a1153..f61080f7bf 100644--- a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts@@ -1,6 +1,38 @@+import JSZip from "jszip";import { describe, expect, it } from "vitest";-import { renderSpreadsheetToCsv } from "./render_to_csv.js";+import { renderSpreadsheetToCsv, renderSpreadsheetToCsvZip } from "./render_to_csv.js";++/** A sheet definition for {@link multiSheetWorkbook}. */+interface SheetSpec {+ id: string;+ name: string;+ hidden?: number;+ cellData: Record<number, Record<number, unknown>>;+}++/** Build a workbook payload from several sheets, preserving their order. */+function multiSheetWorkbook(sheets: SheetSpec[]): string {+ return JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: sheets.map((s) => s.id),+ styles: {},+ sheets: Object.fromEntries(sheets.map((s) => [s.id, { mergeData: [], rowData: {}, columnData: {}, ...s }]))+ }+ });+}++/** Render a zip and read its entries back as `{ name: csvContent }`, BOM stripped. */+async function readZip(buffer: Uint8Array): Promise<Record<string, string>> {+ const zip = await JSZip.loadAsync(buffer);+ const entries: Record<string, string> = {};+ for (const name of Object.keys(zip.files)) {+ const content = await zip.files[name].async("string");+ entries[name] = content.replace(/^\uFEFF/, "");+ }+ return entries;+}/** Build a workbook payload from a sparse cell matrix (keyed by row, then column). */function workbook(@@ -159,3 +191,52 @@ describe("renderSpreadsheetToCsv", () => {expect(() => renderSpreadsheetToCsv(JSON.stringify({ version: 1 }))).toThrow(/no sheets/i);});});++describe("renderSpreadsheetToCsvZip", () => {+ it("emits one BOM-prefixed CSV per visible sheet, named after the sheet", async () => {+ const buffer = await renderSpreadsheetToCsvZip(multiSheetWorkbook([+ { id: "s1", name: "Budget", cellData: { 0: { 0: { v: "a" }, 1: { v: 1 } } } },+ { id: "s2", name: "Notes", cellData: { 0: { 0: { v: "hello" } } } }+ ]));++ const entries = await readZip(buffer);+ expect(Object.keys(entries).sort()).toEqual(["Budget.csv", "Notes.csv"]);+ expect(entries["Budget.csv"]).toBe("a,1");+ expect(entries["Notes.csv"]).toBe("hello");++ // Each entry must keep its UTF-8 BOM (readZip strips it before returning).+ const zip = await JSZip.loadAsync(buffer);+ expect(await zip.files["Budget.csv"].async("string")).toMatch(/^\uFEFF/);+ });++ it("skips hidden sheets", async () => {+ const entries = await readZip(await renderSpreadsheetToCsvZip(multiSheetWorkbook([+ { id: "s1", name: "Visible", cellData: { 0: { 0: { v: "x" } } } },+ { id: "s2", name: "Secret", hidden: 1, cellData: { 0: { 0: { v: "y" } } } }+ ])));+ expect(Object.keys(entries)).toEqual(["Visible.csv"]);+ });++ it("sanitizes illegal filename characters in sheet names", async () => {+ const entries = await readZip(await renderSpreadsheetToCsvZip(multiSheetWorkbook([+ { id: "s1", name: "2026/Q1: a*b?", cellData: { 0: { 0: { v: "v" } } } }+ ])));+ expect(Object.keys(entries)).toEqual(["2026_Q1_ a_b_.csv"]);+ });++ it("de-duplicates colliding sheet names (case-insensitively)", async () => {+ const entries = await readZip(await renderSpreadsheetToCsvZip(multiSheetWorkbook([+ { id: "s1", name: "Sheet", cellData: { 0: { 0: { v: 1 } } } },+ { id: "s2", name: "sheet", cellData: { 0: { 0: { v: 2 } } } },+ { id: "s3", name: "", cellData: { 0: { 0: { v: 3 } } } }+ ])));+ // Each base keeps its own casing; collisions are detected case-insensitively, so "sheet"+ // and the blank name (which falls back to "Sheet") get numbered suffixes.+ expect(Object.keys(entries).sort()).toEqual(["Sheet (3).csv", "Sheet.csv", "sheet (2).csv"]);+ });++ it("throws on unparseable JSON and on a workbook with no sheets", async () => {+ await expect(renderSpreadsheetToCsvZip("not json")).rejects.toThrow(/parse/i);+ await expect(renderSpreadsheetToCsvZip(JSON.stringify({ version: 1 }))).rejects.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.tsindex 69539665a3..143e767a90 100644--- a/packages/commons/src/lib/spreadsheet/render_to_csv.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.ts@@ -14,7 +14,9 @@* 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.+ * active sheet in the editor); absent that, the first visible sheet is used. To export a+ * multi-sheet workbook without losing data, `renderSpreadsheetToCsvZip` emits one CSV per+ * visible sheet bundled into a `.zip`.*/import { format as formatNumfmt, getFormatDateInfo, isDateFormat } from "numfmt";@@ -25,11 +27,15 @@ import {type ICellData,isFiniteNumber,type IStyleData,+ type IWorkbookData,type IWorksheetData,parseWorkbookData,resolveCellStyle} from "./workbook_model.js";+// Prepended to each emitted CSV so Excel auto-detects UTF-8 (it only does so with a BOM).+const UTF8_BOM = "\uFEFF";+export interface CsvRenderOptions {/** Id of the sheet to export. Falls back to the first visible sheet when omitted or not found. */sheetId?: string;@@ -39,24 +45,54 @@ export interface CsvRenderOptions {* 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.+ *+ * Note: the returned string has no UTF-8 BOM, so callers downloading it for Excel should+ * prepend one (the zip variant below does this per entry).*/export function renderSpreadsheetToCsv(jsonContent: string, options: CsvRenderOptions = {}): string {+ const workbook = readWorkbook(jsonContent);+ const visibleSheets = getVisibleSheets(workbook);+ if (visibleSheets.length === 0) {+ return "";+ }++ const sheet = pickSheet(visibleSheets, options.sheetId);+ return renderSheet(sheet, workbook.styles ?? {});+}++/**+ * Renders every visible sheet to its own CSV and bundles them into a `.zip`, returned as a+ * binary buffer. Each entry is named after its sheet (sanitized and de-duplicated) with a+ * UTF-8 BOM. Use this for multi-sheet workbooks, where the single-sheet renderer would+ * silently drop every sheet but one. Throws if the content is not a parseable workbook.+ */+export async function renderSpreadsheetToCsvZip(jsonContent: string): Promise<Uint8Array> {+ const workbook = readWorkbook(jsonContent);+ const styles = workbook.styles ?? {};++ // Dynamic import keeps jszip out of the main bundle (and out of standalone/core).+ const { default: JSZip } = await import("jszip");+ const zip = new JSZip();++ const usedNames = new Set<string>();+ for (const sheet of getVisibleSheets(workbook)) {+ const fileName = uniqueFileName(sheet.name, usedNames);+ zip.file(fileName, UTF8_BOM + renderSheet(sheet, styles));+ }++ return zip.generateAsync({ type: "uint8array" });+}++/** Parses and validates workbook JSON, throwing on unparseable content or a missing workbook. */+function readWorkbook(jsonContent: string): IWorkbookData {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, data.workbook.styles ?? {});+ return data.workbook;}function pickSheet(visibleSheets: IWorksheetData[], sheetId: string | undefined): IWorksheetData {@@ -67,6 +103,24 @@ function pickSheet(visibleSheets: IWorksheetData[], sheetId: string | undefined)return visibleSheets[0];}+/**+ * Turns a sheet name into a safe, unique `<name>.csv` zip entry: illegal filename characters+ * (path separators, `:*?"<>|`, control codes) become `_`, blank names fall back to "Sheet",+ * and collisions get a ` (n)` suffix. De-duplication is case-insensitive so the archive+ * unzips cleanly on case-insensitive filesystems (Windows, macOS).+ */+function uniqueFileName(sheetName: string, usedNames: Set<string>): string {+ const base = (sheetName ?? "").replace(/[\\/:*?"<>|\u0000-\u001f]/g, "_").trim() || "Sheet";++ let candidate = base;+ for (let n = 2; usedNames.has(candidate.toLowerCase()); n++) {+ candidate = `${base} (${n})`;+ }+ usedNames.add(candidate.toLowerCase());++ return `${candidate}.csv`;+}+function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData | null>): string {const { cellData } = sheet;const bounds = computeBounds(cellData, sheet.mergeData);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7ac9b8234c..eba584ac57 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1526,6 +1526,9 @@ importers:exceljs:specifier: 4.4.0version: 4.4.0+ jszip:+ specifier: 3.10.1+ version: 3.10.1marked:specifier: 18.0.4version: 18.0.4