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(import/spreadsheet): support files within ZIPs
Elian Doran5a08bda5a160
diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.tsindex 83f8a76faa..889a691cd5 100644--- a/packages/trilium-core/src/services/import/zip.spec.ts+++ b/packages/trilium-core/src/services/import/zip.spec.ts@@ -1,4 +1,5 @@import { beforeAll, describe, expect, it, vi } from "vitest";+import ExcelJS from "exceljs";import { ZipArchive } from "archiver";import fs from "fs";import { fileURLToPath } from "url";@@ -178,8 +179,48 @@ describe("processNoteContent", () => {expect(content).toContain("/image/image.jpg)");expect(content).not.toContain("Markdown Note_image.jpg");});++ it("imports a CSV entry as an editable spreadsheet note", async () => {+ const zipBuffer = await createZipBuffer({ "csv_import_sample.csv": "a,b\r\n1,2" });+ const { rootNote } = await testImportBuffer(zipBuffer, "import-csv", {});++ const note = rootNote.getChildNotes().find((n) => n.title === "csv_import_sample");+ expect(note?.type).toBe("spreadsheet");+ expect(note?.mime).toBe("text/x-spreadsheet");++ const sheet = parseWorkbookSheet(note?.getContent());+ expect(sheet.cellData[0][0].v).toBe("a");+ expect(sheet.cellData[1][1].v).toBe(2);+ });++ it("imports an XLSX entry as an editable spreadsheet note", async () => {+ const wb = new ExcelJS.Workbook();+ const ws = wb.addWorksheet("Sheet1");+ ws.getCell("A1").value = "hello";+ ws.getCell("B1").value = 42;+ const xlsxBuffer = Buffer.from(await wb.xlsx.writeBuffer());++ const zipBuffer = await createZipBuffer({ "xlsx_import_sample.xlsx": xlsxBuffer });+ const { rootNote } = await testImportBuffer(zipBuffer, "import-xlsx", {});++ const note = rootNote.getChildNotes().find((n) => n.title === "xlsx_import_sample");+ expect(note?.type).toBe("spreadsheet");+ expect(note?.mime).toBe("text/x-spreadsheet");++ const sheet = parseWorkbookSheet(note?.getContent());+ expect(sheet.cellData[0][0].v).toBe("hello");+ expect(sheet.cellData[0][1].v).toBe(42);+ });}, 60_000);+/** Parses a spreadsheet note's content and returns its single (first) sheet's data. */+function parseWorkbookSheet(content: string | Uint8Array | undefined) {+ expect(typeof content).toBe("string");+ const parsed = JSON.parse(content as string);+ const sheetId = parsed.workbook.sheetOrder[0];+ return parsed.workbook.sheets[sheetId];+}+function getNoteByTitlePath(parentNote: BNote, ...titlePath: string[]) {let cursor = parentNote;for (const title of titlePath) {diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.tsindex abd3019b04..23c80e89e6 100644--- a/packages/trilium-core/src/services/import/zip.ts+++ b/packages/trilium-core/src/services/import/zip.ts@@ -21,6 +21,12 @@ import { AttributeMeta, NoteMeta } from "../../meta.js";import { isMarkdownCodeNote } from "../export/rewrite_links.js";import { sanitizeHtml } from "../sanitizer.js";+// Source mimes that import as editable spreadsheet notes (parsed to Univer workbook JSON),+// mirroring the single-file importer. As resolved by `mime-types` from the entry extension.+const CSV_MIME = "text/csv";+const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";+const SPREADSHEET_MIME = "text/x-spreadsheet";+interface MetaFile {files: NoteMeta[];}@@ -174,6 +180,14 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Uifunction detectFileTypeAndMime(taskContext: TaskContext<"importNotes">, filePath: string) {const rawMime = mimeService.getMime(filePath) || "application/octet-stream";++ // CSV/XLSX entries become editable spreadsheet notes (matching single-file import). The+ // raw mime is kept so `saveNote` knows which parser to run; it's swapped for the+ // spreadsheet mime once the bytes have been converted to the Univer workbook JSON.+ if (rawMime === CSV_MIME || rawMime === XLSX_MIME) {+ return { mime: rawMime, type: "spreadsheet" as NoteType };+ }+const type = mimeService.getType(taskContext.data || {}, rawMime);// Normalize aliased code MIMEs (e.g. `text/markdown` → `text/x-markdown`,// `application/javascript` → `text/javascript`) so the@@ -481,7 +495,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Uireturn content;}- function saveNote(filePath: string, content: string | Uint8Array) {+ async function saveNote(filePath: string, content: string | Uint8Array) {const { parentNoteMeta, noteMeta, attachmentMeta } = getMeta(filePath);if (noteMeta?.noImport) {@@ -530,6 +544,14 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Uithrow new Error("Unable to resolve mime type.");}+ // A raw CSV/XLSX entry still holds its source bytes; convert them to the Univer workbook+ // JSON a spreadsheet note stores, then record the spreadsheet mime. Entries from a Trilium+ // export already carry workbook JSON and the spreadsheet mime, so they skip this.+ if (type === "spreadsheet" && (mime === CSV_MIME || mime === XLSX_MIME)) {+ content = await convertSpreadsheetContent(mime, content);+ mime = SPREADSHEET_MIME;+ }+if (type !== "file" && type !== "image") {content = processStringOrBuffer(content);}@@ -662,7 +684,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Uiif (/\/$/.test(entry.fileName)) {saveDirectory(filePath);} else if (filePath !== "!!!meta.json") {- saveNote(filePath, await readContent());+ await saveNote(filePath, await readContent());}taskContext.increaseProgressCount();@@ -739,6 +761,22 @@ function resolveNoteType(type: string | undefined): NoteType {}+/**+ * Parses a raw CSV or XLSX entry into the Univer workbook JSON a spreadsheet note stores.+ * The parsers are dynamically imported so exceljs only loads when such a file is imported+ * (keeping it out of the core barrel and the standalone/browser bundle).+ */+async function convertSpreadsheetContent(mime: string, content: string | Uint8Array): Promise<string> {+ if (mime === XLSX_MIME) {+ const { parseXlsxToWorkbook } = await import("@triliumnext/commons/src/lib/spreadsheet/parse_from_xlsx.js");+ const buffer = typeof content === "string" ? Buffer.from(content) : content;+ return JSON.stringify(await parseXlsxToWorkbook(buffer));+ }++ const { parseCsvToWorkbook } = await import("@triliumnext/commons/src/lib/spreadsheet/parse_from_csv.js");+ return JSON.stringify(parseCsvToWorkbook(processStringOrBuffer(content)));+}+export function removeTriliumTags(content: string) {const tagsToRemove = ["<h1 data-trilium-h1>([^<]*)<\/h1>",