Skip to content

Build your personal knowledge base with Trilium Notes

feat(spreadsheet): wire importing XLSX

Elian Doran69fd28c060e3
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
index 03035eb83c..d90dc102fd 100644
--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
@@ -48,9 +48,7 @@ const DEFAULT_COLUMN_COUNT = 20;
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);
+ await wb.xlsx.load(toArrayBuffer(input));
} catch {
throw new Error("Unable to parse spreadsheet file.");
}
@@ -185,7 +183,11 @@ function assignPrimitive(data: ICellData, result: ExcelJS.Cell["result"]): void
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; }
+ if (typeof result === "object" && result !== null && "error" in result) {
+ data.v = String((result as ExcelJS.CellErrorValue).error);
+ data.t = CellValueType.FORCE_STRING;
+ return;
+ }
data.v = String(result);
data.t = CellValueType.STRING;
}
@@ -377,10 +379,12 @@ function solidFillColor(fill: ExcelJS.Fill | undefined): Partial<ExcelJS.Color>
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];
+ // exceljs' `Color` type omits `tint`, though it's present on theme colors at runtime.
+ const themed = color as { theme?: number; tint?: number };
+ if (typeof themed.theme === "number") {
+ const base = THEME_COLORS[themed.theme];
if (!base) return null;
- return applyTint(base, isFiniteNumber(color.tint) ? color.tint : 0);
+ return applyTint(base, isFiniteNumber(themed.tint) ? themed.tint : 0);
}
return null;
}
@@ -510,3 +514,14 @@ function dateToSerial(date: Date): number {
function isFiniteNumber(v: unknown): v is number {
return typeof v === "number" && Number.isFinite(v);
}
+
+/**
+ * Normalizes input to a tight `ArrayBuffer` for exceljs. A `Uint8Array`/Node `Buffer` can be a
+ * view into a larger pooled buffer, so reading `.buffer` directly would include foreign bytes —
+ * slice by its offset/length when it isn't already a full-buffer view.
+ */
+function toArrayBuffer(input: ArrayBuffer | Uint8Array): ArrayBuffer {
+ if (!(input instanceof Uint8Array)) return input;
+ // `slice()` copies into a fresh, tightly-sized ArrayBuffer — independent of any pool.
+ return input.slice().buffer as ArrayBuffer;
+}
diff --git a/packages/trilium-core/src/routes/api/import.ts b/packages/trilium-core/src/routes/api/import.ts
index 15ce84860a..91f0feb2ee 100644
--- a/packages/trilium-core/src/routes/api/import.ts
+++ b/packages/trilium-core/src/routes/api/import.ts
@@ -69,7 +69,7 @@ async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>)
return importResult;
}
} else {
- note = singleImportService.importSingleFile(taskContext, file, parentNote);
+ note = await singleImportService.importSingleFile(taskContext, file, parentNote);
}
} catch (e: unknown) {
const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);
diff --git a/packages/trilium-core/src/services/import/single.spec.ts b/packages/trilium-core/src/services/import/single.spec.ts
index a749647fb6..4eafa1bf6d 100644
--- a/packages/trilium-core/src/services/import/single.spec.ts
+++ b/packages/trilium-core/src/services/import/single.spec.ts
@@ -1,4 +1,5 @@
import { beforeAll, describe, expect, it, vi } from "vitest";
+import ExcelJS from "exceljs";
import fs from "fs";
import { fileURLToPath } from "url";
import { dirname } from "path";
@@ -11,8 +12,8 @@ import stripBom from "strip-bom";
import { getContext } from "../context.js";
const scriptDir = dirname(fileURLToPath(import.meta.url));
-async function testImport(fileName: string, mimetype: string) {
- const buffer = fs.readFileSync(`${scriptDir}/samples/${fileName}`);
+async function testImport(fileName: string, mimetype: string, bufferOverride?: Buffer) {
+ const buffer = bufferOverride ?? fs.readFileSync(`${scriptDir}/samples/${fileName}`);
const taskContext = TaskContext.getInstance("import-mdx", "importNotes", {
textImportedAsText: true,
codeImportedAsCode: true
@@ -26,7 +27,7 @@ async function testImport(fileName: string, mimetype: string) {
return;
}
- const importedNote = single.importSingleFile(
+ const importedNote = await single.importSingleFile(
taskContext,
{
originalname: fileName,
@@ -116,4 +117,31 @@ describe("processNoteContent", () => {
title: "New note"
});
});
+
+ it("imports .xlsx as a 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 { importedNote } = await testImport(
+ "Budget.xlsx",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ xlsxBuffer
+ );
+
+ expect(importedNote).toMatchObject({
+ mime: "text/x-spreadsheet",
+ type: "spreadsheet",
+ title: "Budget"
+ });
+ expect(importedNote.getLabelValue("originalFileName")).toBe("Budget.xlsx");
+
+ // Content is the persisted Univer workbook with our imported values.
+ const parsed = JSON.parse(importedNote.getContent().toString());
+ const sheet = parsed.workbook.sheets[parsed.workbook.sheetOrder[0]];
+ expect(sheet.cellData[0][0].v).toBe("Hello");
+ expect(sheet.cellData[0][1].v).toBe(42);
+ });
}, 60_000);
diff --git a/packages/trilium-core/src/services/import/single.ts b/packages/trilium-core/src/services/import/single.ts
index 87cb07da64..5dd866cc41 100644
--- a/packages/trilium-core/src/services/import/single.ts
+++ b/packages/trilium-core/src/services/import/single.ts
@@ -13,7 +13,10 @@ import { getNoteTitle } from "../utils/index.js";
import { sanitizeHtml } from "../sanitizer.js";
import { processStringOrBuffer } from "../utils/binary.js";
-function importSingleFile(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
+// MIME of an `.xlsx` upload (Office Open XML spreadsheet), as resolved by `mime-types`.
+const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
+
+async function importSingleFile(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
const mime = mimeService.getMime(file.originalname) || file.mimetype;
if (taskContext?.data?.textImportedAsText) {
@@ -26,6 +29,13 @@ function importSingleFile(taskContext: TaskContext<"importNotes">, file: File, p
}
}
+ // TODO: gate behind an import option (e.g. `spreadsheetImportedAsSpreadsheet`) once exposed,
+ // mirroring `textImportedAsText`/`codeImportedAsCode`. For now an `.xlsx` always becomes an
+ // editable spreadsheet note rather than an opaque attachment.
+ if (mime === XLSX_MIME) {
+ return importSpreadsheet(taskContext, file, parentNote);
+ }
+
if (mime === "text/vnd.mermaid") {
return importCustomType(taskContext, file, parentNote, "mermaid", mime);
}
@@ -115,6 +125,32 @@ function importCustomType(taskContext: TaskContext<"importNotes">, file: File, p
return note;
}
+async function importSpreadsheet(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
+ const title = getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
+
+ // Dynamically import the exceljs-backed parser so exceljs only loads when an `.xlsx` is
+ // actually imported, keeping it out of the core barrel (and the standalone/browser bundle).
+ const { parseXlsxToWorkbook } = await import("@triliumnext/commons/src/lib/spreadsheet/parse_from_xlsx.js");
+ const buffer = typeof file.buffer === "string" ? Buffer.from(file.buffer) : file.buffer;
+ const workbook = await parseXlsxToWorkbook(buffer);
+ const content = JSON.stringify(workbook);
+
+ const { note } = noteService.createNewNote({
+ parentNoteId: parentNote.noteId,
+ title,
+ content,
+ type: "spreadsheet",
+ mime: "text/x-spreadsheet",
+ isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()
+ });
+
+ note.addLabel("originalFileName", file.originalname);
+
+ taskContext.increaseProgressCount();
+
+ return note;
+}
+
function importPlainText(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
const title = getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
const plainTextContent = processStringOrBuffer(file.buffer);
diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.ts
index b125ffb0bf..9b39ba759d 100644
--- a/packages/trilium-core/src/services/utils/index.ts
+++ b/packages/trilium-core/src/services/utils/index.ts
@@ -282,6 +282,7 @@ export function removeFileExtension(filePath: string, mime?: string) {
case ".mermaid":
case ".mmd":
case ".pdf":
+ case ".xlsx":
return filePath.substring(0, filePath.length - extension.length);
default:
return filePath;