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(office): render XLSX previews with the native spreadsheet pipeline
Elian Doran15e9711415f2
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.tsindex 2d1a701048..aad13176ea 100644--- a/packages/trilium-core/src/routes/api/files.spec.ts+++ b/packages/trilium-core/src/routes/api/files.spec.ts@@ -1,6 +1,10 @@+import ExcelJS from "exceljs";import { beforeAll, describe, expect, it } from "vitest";+import becca from "../../becca/becca.js";+import * as cls from "../../services/context.js";import protectedSessionService from "../../services/protected_session";+import { getSql } from "../../services/sql/index.js";import { encodeUtf8 } from "../../services/utils/binary";import { createTextNote } from "../../test/api_fixtures";import { CoreApiTester } from "../../test/api_tester";@@ -169,5 +173,56 @@ describe("Files API (core)", () => {const res = await api.get("/api/notes/missingNote123/office-preview");expect(res.status).toBe(404);});++ it("renders an XLSX note through the native spreadsheet pipeline", async () => {+ const wb = new ExcelJS.Workbook();+ const sheet = wb.addWorksheet("Data");+ sheet.getCell("A1").value = "Merged header";+ sheet.mergeCells("A1:B1");+ const amount = sheet.getCell("A2");+ amount.value = 1234.5;+ amount.numFmt = "#,##0.00";+ amount.border = { top: { style: "thin" }, bottom: { style: "thin" } };+ const xlsxBuffer = Buffer.from(await wb.xlsx.writeBuffer());++ const noteId = await createXlsxNote(xlsxBuffer);++ const res = await api.get<{ html: string }>(`/api/notes/${noteId}/office-preview`);+ expect(res.status).toBe(200);+ expect(res.body.html).toContain("Merged header");+ // Native-renderer features officeparser's grid lacks: merged cells,+ // number formatting (numfmt) and inline borders...+ expect(res.body.html).toContain('colspan="2"');+ expect(res.body.html).toContain("1,234.50");+ expect(res.body.html).toContain("border");+ // ...and none of officeparser's class-styled A/B/C header chrome.+ expect(res.body.html).not.toContain("excel-col-header");+ });});});++/**+ * Creates a file note holding a binary `.xlsx` workbook. The JSON note-creation API cannot+ * carry binary content, so the note is created empty through the API and the buffer is+ * written through becca (same pattern as the image route spec).+ */+async function createXlsxNote(xlsxBuffer: Buffer): Promise<string> {+ const res = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {+ body: {+ title: "workbook.xlsx",+ type: "file",+ mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ content: ""+ }+ });+ expect(res.status).toBe(200);+ const noteId = res.body.note.noteId;++ cls.init(() =>+ getSql().transactional(() => {+ becca.getNoteOrThrow(noteId).setContent(xlsxBuffer, { forceSave: true });+ })+ );++ return noteId;+}diff --git a/packages/trilium-core/src/services/office_preview.ts b/packages/trilium-core/src/services/office_preview.tsindex 0c8585e2f0..9e694ab052 100644--- a/packages/trilium-core/src/services/office_preview.ts+++ b/packages/trilium-core/src/services/office_preview.ts@@ -10,10 +10,18 @@ import { wrapStringOrBuffer } from "./utils/binary.js";*/const MAX_OFFICE_PREVIEW_BYTES = 20 * 1024 * 1024;+// MIME of an `.xlsx` upload (Office Open XML spreadsheet), previewed through the native+// spreadsheet pipeline rather than officeparser.+const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";+/*** Converts an office document (DOCX/XLSX/PPTX, ODT/ODS/ODP, RTF and EPUB) to an embeddable- * HTML fragment using officeparser. The heavy library is loaded lazily on first use- * (dynamic import), so it never weighs on the initial standalone bundle.+ * HTML fragment. XLSX goes through Trilium's own spreadsheet pipeline (the same one behind+ * Spreadsheet notes, sharing and printing): unlike officeparser's grid, it renders borders,+ * merged cells, column widths and number formats, and styles everything inline so the+ * output needs no accompanying stylesheet. Everything else is converted by officeparser.+ * Both libraries are loaded lazily on first use (dynamic import), so neither weighs on the+ * initial standalone bundle.** The result is NOT sanitized — the client must sanitize it before injecting into the DOM.*/@@ -27,6 +35,15 @@ export async function convertOfficeToHtml(content: string | Uint8Array, mime: stthrow new ValidationError(`Office document is too large to preview (${buffer.byteLength} bytes).`);}+ if (mime === XLSX_MIME) {+ try {+ return await convertXlsxToHtml(buffer);+ } catch {+ // Not a workbook exceljs can read (e.g. a mislabeled or exotic file) —+ // fall through and let officeparser have a go at it.+ }+ }+const fileType = OFFICE_FILE_TYPE_HINTS[mime];const { OfficeConverter } = await import("officeparser");const { value } = await OfficeConverter.convert(buffer, "html", {@@ -46,3 +63,22 @@ export async function convertOfficeToHtml(content: string | Uint8Array, mime: st// value is a string for the 'html' destination.return typeof value === "string" ? value : "";}++/**+ * Renders an `.xlsx` workbook through the native spreadsheet pipeline: the same+ * parse-to-Univer-JSON step the importer uses, then the shared/print HTML renderer.+ * Dynamically imported so exceljs only loads when an `.xlsx` is actually previewed,+ * keeping it out of the core barrel (and the standalone/browser bundle).+ */+async function convertXlsxToHtml(buffer: Uint8Array): Promise<string> {+ const [{ parseXlsxToWorkbook }, { renderSpreadsheetToHtml }] = await Promise.all([+ import("@triliumnext/commons/src/lib/spreadsheet/parse_from_xlsx.js"),+ import("@triliumnext/commons/src/lib/spreadsheet/render_to_html.js")+ ]);++ const workbook = await parseXlsxToWorkbook(buffer);++ // The renderer consumes the persisted note-content shape, which is the stringified+ // parse result (see importSpreadsheet in the import service).+ return renderSpreadsheetToHtml(JSON.stringify(workbook));+}