Skip to content

Build your personal knowledge base with Trilium Notes

feat(import/spreadsheet): basic CSV import format

Elian Doran0edbdc9358d5
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_csv.spec.ts b/packages/commons/src/lib/spreadsheet/parse_from_csv.spec.ts
new file mode 100644
index 0000000000..f89d387972
--- /dev/null
+++ b/packages/commons/src/lib/spreadsheet/parse_from_csv.spec.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from "vitest";
+
+import { parseCsvToWorkbook } from "./parse_from_csv.js";
+import { CellValueType, type ICellData, type IWorksheetData } from "./workbook_model.js";
+
+/** Parse CSV and return the single sheet. */
+function sheet(csv: string): IWorksheetData {
+ const { workbook } = parseCsvToWorkbook(csv);
+ return workbook.sheets[workbook.sheetOrder[0]];
+}
+
+/** The cell at (row, col), or undefined when no cell was emitted. */
+function cell(ws: IWorksheetData, row: number, col: number): ICellData | undefined {
+ return ws.cellData[row]?.[col];
+}
+
+describe("parseCsvToWorkbook", () => {
+ it("produces a single sheet laid out by row and column", () => {
+ const ws = sheet("a,b,c\r\nd,e,f");
+ expect(workbookShape("a,b,c\r\nd,e,f")).toEqual([
+ ["a", "b", "c"],
+ ["d", "e", "f"]
+ ]);
+ expect(ws.id).toBe("sheet-0");
+ // Grid grows to at least Univer's defaults.
+ expect(ws.rowCount).toBe(1000);
+ expect(ws.columnCount).toBe(20);
+ });
+
+ it("accepts LF, CRLF and CR record terminators", () => {
+ expect(workbookShape("a,b\nc,d")).toEqual([["a", "b"], ["c", "d"]]);
+ expect(workbookShape("a,b\r\nc,d")).toEqual([["a", "b"], ["c", "d"]]);
+ expect(workbookShape("a,b\rc,d")).toEqual([["a", "b"], ["c", "d"]]);
+ });
+
+ it("infers numbers and booleans, leaving other text alone", () => {
+ const ws = sheet("42,1234.5,-5,TRUE,FALSE,hello");
+ expect(cell(ws, 0, 0)).toEqual({ v: 42, t: CellValueType.NUMBER });
+ expect(cell(ws, 0, 1)).toEqual({ v: 1234.5, t: CellValueType.NUMBER });
+ expect(cell(ws, 0, 2)).toEqual({ v: -5, t: CellValueType.NUMBER });
+ expect(cell(ws, 0, 3)).toEqual({ v: true, t: CellValueType.BOOLEAN });
+ expect(cell(ws, 0, 4)).toEqual({ v: false, t: CellValueType.BOOLEAN });
+ expect(cell(ws, 0, 5)).toEqual({ v: "hello", t: CellValueType.STRING });
+ });
+
+ it("keeps numeric-looking text that would not round-trip as a string", () => {
+ const ws = sheet("007,1e3,+1,1.0,2026-04-06");
+ expect(cell(ws, 0, 0)).toEqual({ v: "007", t: CellValueType.STRING });
+ expect(cell(ws, 0, 1)).toEqual({ v: "1e3", t: CellValueType.STRING });
+ expect(cell(ws, 0, 2)).toEqual({ v: "+1", t: CellValueType.STRING });
+ expect(cell(ws, 0, 3)).toEqual({ v: "1.0", t: CellValueType.STRING });
+ // Dates have no CSV type, so they stay text.
+ expect(cell(ws, 0, 4)).toEqual({ v: "2026-04-06", t: CellValueType.STRING });
+ });
+
+ it("unquotes RFC 4180 fields (doubled quotes, embedded commas and newlines)", () => {
+ const ws = sheet('"a,b","he said ""hi""","line1\nline2"');
+ expect(cell(ws, 0, 0)?.v).toBe("a,b");
+ expect(cell(ws, 0, 1)?.v).toBe('he said "hi"');
+ expect(cell(ws, 0, 2)?.v).toBe("line1\nline2");
+ });
+
+ it("emits no cell for an empty field but keeps surrounding ones", () => {
+ const ws = sheet("a,,c");
+ expect(cell(ws, 0, 0)?.v).toBe("a");
+ expect(cell(ws, 0, 1)).toBeUndefined();
+ expect(cell(ws, 0, 2)?.v).toBe("c");
+ });
+
+ it("ignores a single trailing newline but preserves interior blank rows", () => {
+ expect(workbookShape("a\n")).toEqual([["a"]]);
+ // A blank middle line is a real (empty) record between two populated rows.
+ const ws = sheet("a\n\nb");
+ expect(cell(ws, 0, 0)?.v).toBe("a");
+ expect(cell(ws, 1, 0)).toBeUndefined();
+ expect(cell(ws, 2, 0)?.v).toBe("b");
+ });
+
+ it("strips a leading UTF-8 BOM (as written by the exporter)", () => {
+ const ws = sheet("name,age");
+ expect(cell(ws, 0, 0)?.v).toBe("name");
+ });
+
+ it("returns an empty sheet for empty input", () => {
+ const ws = sheet("");
+ expect(ws.cellData).toEqual({});
+ });
+});
+
+/** Reduce the parsed workbook back to a plain matrix of cell values for shape assertions. */
+function workbookShape(csv: string): unknown[][] {
+ const ws = sheet(csv);
+ const rows = Object.keys(ws.cellData).map(Number).sort((a, b) => a - b);
+ return rows.map((r) => {
+ const cols = Object.keys(ws.cellData[r]).map(Number).sort((a, b) => a - b);
+ return cols.map((c) => ws.cellData[r][c].v);
+ });
+}
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_csv.ts b/packages/commons/src/lib/spreadsheet/parse_from_csv.ts
new file mode 100644
index 0000000000..b353634c5a
--- /dev/null
+++ b/packages/commons/src/lib/spreadsheet/parse_from_csv.ts
@@ -0,0 +1,131 @@
+/**
+ * Parses CSV text into a UniversJS workbook JSON structure — the inverse of `render_to_csv`.
+ * The result matches the `PersistedData` shape a spreadsheet note stores, so the output can be
+ * stringified straight into note content (same as `parse_from_xlsx`).
+ *
+ * CSV carries only values, so the workbook is a single unstyled sheet. Field parsing follows
+ * RFC 4180 (quoted fields, doubled quotes, embedded commas/newlines); records may end in CRLF,
+ * LF or CR. A leading UTF-8 BOM (which our own exporter writes for Excel) is stripped.
+ *
+ * Values are inferred conservatively: `TRUE`/`FALSE` become booleans, and a field becomes a
+ * number only when it round-trips exactly (so `007`, `1,000`, `+1`, `1e3` and the like stay
+ * text rather than being silently mangled). Everything else — including dates, which CSV has
+ * no type for — stays a string.
+ */
+
+import {
+ CellValueType,
+ type ICellData,
+ type IWorksheetData,
+ type PersistedData
+} from "./workbook_model.js";
+
+/** Univer's default grid size for a fresh sheet; the imported sheet is grown to fit its data. */
+const DEFAULT_ROW_COUNT = 1000;
+const DEFAULT_COLUMN_COUNT = 20;
+
+const SHEET_ID = "sheet-0";
+
+/** Parses CSV text and produces a single-sheet UniversJS workbook. */
+export function parseCsvToWorkbook(csvText: string): PersistedData {
+ const rows = parseCsv(stripBom(csvText));
+ const cellData = buildCellData(rows);
+ const maxColumns = rows.reduce((max, row) => Math.max(max, row.length), 0);
+
+ const sheet: IWorksheetData = {
+ id: SHEET_ID,
+ name: "Sheet1",
+ cellData,
+ // Grow the grid past Univer's defaults when the data needs it, so nothing is clipped.
+ rowCount: Math.max(DEFAULT_ROW_COUNT, rows.length),
+ columnCount: Math.max(DEFAULT_COLUMN_COUNT, maxColumns)
+ };
+
+ return {
+ version: 1,
+ workbook: {
+ sheetOrder: [SHEET_ID],
+ styles: {},
+ sheets: { [SHEET_ID]: sheet }
+ }
+ };
+}
+
+/**
+ * Tokenizes CSV into a matrix of string fields. A single trailing record terminator does not
+ * produce a spurious empty final row, but genuine blank lines in the middle are preserved.
+ */
+function parseCsv(text: string): string[][] {
+ const rows: string[][] = [];
+ let row: string[] = [];
+ let field = "";
+ let inQuotes = false;
+ let i = 0;
+
+ while (i < text.length) {
+ const ch = text[i];
+
+ if (inQuotes) {
+ if (ch === "\"") {
+ // A doubled quote inside a quoted field is a literal quote; a lone one closes it.
+ if (text[i + 1] === "\"") { field += "\""; i += 2; continue; }
+ inQuotes = false; i++; continue;
+ }
+ field += ch; i++; continue;
+ }
+
+ if (ch === "\"") { inQuotes = true; i++; continue; }
+ if (ch === ",") { row.push(field); field = ""; i++; continue; }
+ if (ch === "\n") { row.push(field); field = ""; rows.push(row); row = []; i++; continue; }
+ if (ch === "\r") {
+ row.push(field); field = ""; rows.push(row); row = [];
+ i += text[i + 1] === "\n" ? 2 : 1; // swallow the LF of a CRLF pair
+ continue;
+ }
+
+ field += ch; i++;
+ }
+
+ row.push(field);
+ rows.push(row);
+
+ // A trailing terminator leaves a final [""] record; drop it (but keep real empty fields).
+ const last = rows[rows.length - 1];
+ if (last.length === 1 && last[0] === "") rows.pop();
+
+ return rows;
+}
+
+function buildCellData(rows: string[][]): Record<number, Record<number, ICellData>> {
+ const cellData: Record<number, Record<number, ICellData>> = {};
+
+ rows.forEach((row, r) => {
+ row.forEach((value, c) => {
+ const cell = toCell(value);
+ if (cell) (cellData[r] ??= {})[c] = cell;
+ });
+ });
+
+ return cellData;
+}
+
+/** Infers a typed cell from a raw field, or `null` for an empty field (no cell emitted). */
+function toCell(value: string): ICellData | null {
+ if (value === "") return null;
+
+ if (value === "TRUE") return { v: true, t: CellValueType.BOOLEAN };
+ if (value === "FALSE") return { v: false, t: CellValueType.BOOLEAN };
+
+ // Treat as a number only when the canonical form is byte-identical, so values that merely
+ // look numeric (leading zeros, thousands separators, exponents, signs) keep their text.
+ const num = Number(value);
+ if (Number.isFinite(num) && String(num) === value) {
+ return { v: num, t: CellValueType.NUMBER };
+ }
+
+ return { v: value, t: CellValueType.STRING };
+}
+
+function stripBom(text: string): string {
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
+}
diff --git a/packages/trilium-core/src/services/import/single.ts b/packages/trilium-core/src/services/import/single.ts
index 5dd866cc41..c1ddd329f8 100644
--- a/packages/trilium-core/src/services/import/single.ts
+++ b/packages/trilium-core/src/services/import/single.ts
@@ -15,6 +15,8 @@ import { processStringOrBuffer } from "../utils/binary.js";
// MIME of an `.xlsx` upload (Office Open XML spreadsheet), as resolved by `mime-types`.
const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
+// MIME of a `.csv` upload, as resolved by `mime-types`.
+const CSV_MIME = "text/csv";
async function importSingleFile(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
const mime = mimeService.getMime(file.originalname) || file.mimetype;
@@ -36,6 +38,10 @@ async function importSingleFile(taskContext: TaskContext<"importNotes">, file: F
return importSpreadsheet(taskContext, file, parentNote);
}
+ if (mime === CSV_MIME) {
+ return importSpreadsheetFromCsv(taskContext, file, parentNote);
+ }
+
if (mime === "text/vnd.mermaid") {
return importCustomType(taskContext, file, parentNote, "mermaid", mime);
}
@@ -126,14 +132,25 @@ function importCustomType(taskContext: TaskContext<"importNotes">, file: File, p
}
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);
+
+ return createSpreadsheetNote(taskContext, file, parentNote, JSON.stringify(workbook));
+}
+
+async function importSpreadsheetFromCsv(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote) {
+ const csv = processStringOrBuffer(file.buffer);
+ const { parseCsvToWorkbook } = await import("@triliumnext/commons/src/lib/spreadsheet/parse_from_csv.js");
+ const workbook = parseCsvToWorkbook(csv);
+
+ return createSpreadsheetNote(taskContext, file, parentNote, JSON.stringify(workbook));
+}
+
+function createSpreadsheetNote(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote, content: string) {
+ const title = getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
const { note } = noteService.createNewNote({
parentNoteId: parentNote.noteId,