Skip to content

Build your personal knowledge base with Trilium Notes

fix(spreadsheet): preserve dropdown/data validation on XLSX import

Elian Dorane490809e73fd
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts
index 24be29d0a8..58c8893acb 100644
--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts
@@ -5,6 +5,7 @@ import { excelColorToRgb, parseRange, parseXlsxToWorkbook, toArrayBuffer } from
import {
BorderStyle,
CellValueType,
+ type DataValidationRule,
HorizontalAlign,
type ICellData,
type IStyleData,
@@ -548,6 +549,133 @@ describe("parseXlsxToWorkbook images", () => {
});
});
+describe("parseXlsxToWorkbook data validation", () => {
+ // Reads the SHEET_DATA_VALIDATION_PLUGIN resource for a sheet back into a typed shape.
+ function validationsOf(
+ workbook: { sheetOrder: string[]; resources?: { name: string; data: string }[] },
+ sheetIndex = 0
+ ): DataValidationRule[] | null {
+ const resource = workbook.resources?.find((r) => r.name === "SHEET_DATA_VALIDATION_PLUGIN");
+ if (!resource) return null;
+ const parsed = JSON.parse(resource.data) as Record<string, DataValidationRule[]>;
+ return parsed[workbook.sheetOrder[sheetIndex]] ?? null;
+ }
+
+ it("imports an inline dropdown list, coalescing the cell range and JSON-encoding the options", async () => {
+ // Mirrors the real file: a single sqref rectangle that exceljs expands to individual cells.
+ const wb = new ExcelJS.Workbook();
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = "x";
+ ws.dataValidations.add("D2:E3", {
+ type: "list",
+ allowBlank: true,
+ formulae: ['"0 - Below Expectations ,1 - Meets Expectations,2 - Strong Performance"']
+ });
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+
+ const rules = validationsOf(workbook);
+ expect(rules).toHaveLength(1);
+ const rule = rules?.[0];
+ expect(rule?.type).toBe("list");
+ // Univer's list validator JSON-parses formula1 (deserializeListOptions); the exporter
+ // JSON.stringifies. The inline options keep their exact text, including the trailing space.
+ expect(rule?.formula1).toBe(
+ JSON.stringify(["0 - Below Expectations ", "1 - Meets Expectations", "2 - Strong Performance"])
+ );
+ // The 2x2 block collapses back into a single rectangle, not four 1x1 ranges.
+ expect(rule?.ranges).toEqual([{ startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 }]);
+ expect(rule?.uid).toBeTruthy();
+ });
+
+ it("carries the operator and both formulae for a numeric (whole between) validation", async () => {
+ const wb = new ExcelJS.Workbook();
+ const ws = wb.addWorksheet("S");
+ ws.getCell("B2").dataValidation = { type: "whole", operator: "between", formulae: [1, 10] };
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+
+ const rule = validationsOf(workbook)?.[0];
+ expect(rule?.type).toBe("whole");
+ expect(rule?.operator).toBe("between");
+ expect(rule?.formula1).toBe("1");
+ expect(rule?.formula2).toBe("10");
+ expect(rule?.ranges).toEqual([{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }]);
+ });
+
+ it("emits no validation resource for a sheet without any", async () => {
+ const wb = new ExcelJS.Workbook();
+ wb.addWorksheet("S").getCell("A1").value = "x";
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+ expect(workbook.resources?.some((r) => r.name === "SHEET_DATA_VALIDATION_PLUGIN")).toBeFalsy();
+ });
+
+ it("keeps distinct configs as separate rules on the same sheet", async () => {
+ const wb = new ExcelJS.Workbook();
+ const ws = wb.addWorksheet("S");
+ ws.dataValidations.add("A1:A2", { type: "list", formulae: ['"a,b"'] });
+ ws.dataValidations.add("C1:C2", { type: "list", formulae: ['"x,y"'] });
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+
+ const rules = validationsOf(workbook);
+ expect(rules).toHaveLength(2);
+ const formula1s = rules?.map((r) => r.formula1).sort();
+ expect(formula1s).toEqual([JSON.stringify(["a", "b"]), JSON.stringify(["x", "y"])]);
+ });
+
+ it("passes a range-referenced list through as the formula, not a JSON option array", async () => {
+ // A dropdown whose options come from a cell range ($A$1:$A$3) rather than inline text:
+ // there are no literal options to encode, so the reference is carried as formula1 verbatim.
+ const wb = new ExcelJS.Workbook();
+ const ws = wb.addWorksheet("S");
+ ws.getCell("C1").dataValidation = { type: "list", formulae: ["$A$1:$A$3"] };
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+
+ const rule = validationsOf(workbook)?.[0];
+ expect(rule?.type).toBe("list");
+ expect(rule?.formula1).toBe("$A$1:$A$3");
+ });
+
+ it("carries a single-bound numeric constraint (greaterThan) with just formula1", async () => {
+ const wb = new ExcelJS.Workbook();
+ const ws = wb.addWorksheet("S");
+ ws.getCell("B2").dataValidation = { type: "decimal", operator: "greaterThan", formulae: [5] };
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+
+ const rule = validationsOf(workbook)?.[0];
+ expect(rule?.operator).toBe("greaterThan");
+ expect(rule?.formula1).toBe("5");
+ expect(rule?.formula2).toBeUndefined();
+ });
+
+ it("carries a custom-formula validation (a formula, no operator)", async () => {
+ const wb = new ExcelJS.Workbook();
+ const ws = wb.addWorksheet("S");
+ ws.getCell("B2").dataValidation = { type: "custom", formulae: ["=B2>0"] };
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+
+ const rule = validationsOf(workbook)?.[0];
+ expect(rule?.type).toBe("custom");
+ expect(rule?.formula1).toBe("=B2>0");
+ expect(rule?.operator).toBeUndefined();
+ });
+
+ it("drops a list validation that carries no options", async () => {
+ const wb = new ExcelJS.Workbook();
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = "x";
+ ws.getCell("B1").dataValidation = { type: "list", formulae: [] };
+ const buffer = await wb.xlsx.writeBuffer();
+ const { workbook } = await parseXlsxToWorkbook(buffer as ArrayBuffer);
+ expect(workbook.resources?.some((r) => r.name === "SHEET_DATA_VALIDATION_PLUGIN")).toBeFalsy();
+ });
+});
+
describe("toArrayBuffer", () => {
it("copies a Node Buffer view into a tightly-sized ArrayBuffer, not the whole backing", () => {
// Buffer.prototype.slice returns a VIEW over the same backing (unlike
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
index e439db80b0..a08bee9e43 100644
--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
@@ -9,8 +9,9 @@
* heavy lifting (unzip + XML) is delegated to `exceljs`.
*
* Known fidelity gaps (Excel features Univer's cell model — and our exporter — don't carry):
- * conditional formatting, data validation, filters, charts, embedded images, comments,
- * frozen panes and defined names are dropped. Rich text is flattened to plain text and
+ * conditional formatting, filters, charts, comments, frozen panes and defined names are dropped.
+ * Data validation is carried for the common constraint types (dropdown lists, numeric/date/text
+ * bounds) via the SHEET_DATA_VALIDATION_PLUGIN resource. Rich text is flattened to plain text and
* hyperlinks keep their display text but lose the link. Theme/indexed colors are resolved
* against the standard Office palette (see `THEME_COLORS`), which is approximate when the
* file ships a custom theme.
@@ -21,6 +22,7 @@ import ExcelJS from "exceljs";
import {
BorderStyle,
CellValueType,
+ type DataValidationRule,
HorizontalAlign,
type IBorderData,
type IBorderStyleData,
@@ -32,6 +34,7 @@ import {
type IWorkbookData,
type IWorksheetData,
type PersistedData,
+ SHEET_DATA_VALIDATION_RESOURCE,
SHEET_DRAWING_RESOURCE,
VerticalAlign,
WrapStrategy
@@ -61,6 +64,7 @@ export async function parseXlsxToWorkbook(input: ArrayBuffer | Uint8Array): Prom
const sheetOrder: string[] = [];
const sheets: Record<string, IWorksheetData> = {};
const drawingsBySheet: Record<string, SheetDrawings> = {};
+ const validationsBySheet: Record<string, DataValidationRule[]> = {};
wb.eachSheet((ws, sheetIndex) => {
// Deterministic ids keyed off position; the workbook id/locale are reassigned on load
@@ -72,15 +76,25 @@ export async function parseXlsxToWorkbook(input: ArrayBuffer | Uint8Array): Prom
const drawings = readImages(wb, ws, sheet, id);
if (drawings) drawingsBySheet[id] = drawings;
+
+ const validations = readDataValidations(ws, id);
+ if (validations.length > 0) validationsBySheet[id] = validations;
});
const workbook: IWorkbookData = { sheetOrder, styles: {}, sheets };
- // Floating images go in the SHEET_DRAWING_PLUGIN resource (a JSON string keyed by sheet id),
- // the same shape the editor persists; Univer reconciles the drawing unitId on load.
+ // Both plugin payloads are JSON strings keyed by sheet id, matching the shape the editor
+ // persists; Univer reconciles their unit ids on load.
+ const resources: IWorkbookData["resources"] = [];
+ // Floating images go in the SHEET_DRAWING_PLUGIN resource.
if (Object.keys(drawingsBySheet).length > 0) {
- workbook.resources = [{ name: SHEET_DRAWING_RESOURCE, data: JSON.stringify(drawingsBySheet) }];
+ resources.push({ name: SHEET_DRAWING_RESOURCE, data: JSON.stringify(drawingsBySheet) });
+ }
+ // Data-validation rules (dropdowns, numeric/date bounds) go in the SHEET_DATA_VALIDATION_PLUGIN resource.
+ if (Object.keys(validationsBySheet).length > 0) {
+ resources.push({ name: SHEET_DATA_VALIDATION_RESOURCE, data: JSON.stringify(validationsBySheet) });
}
+ if (resources.length > 0) workbook.resources = resources;
return { version: 1, workbook };
}
@@ -309,6 +323,133 @@ function bytesToBase64(bytes: Uint8Array): string {
// #endregion
+// #region Data validation
+
+/** A 0-based cell coordinate, used while coalescing per-cell validations back into ranges. */
+interface CellRef {
+ row: number;
+ column: number;
+}
+
+/**
+ * Reads a worksheet's data-validation rules into Univer rules. exceljs expands a rule's `sqref`
+ * (e.g. `D2:I6`) into one entry per cell, so cells sharing an identical config are grouped and
+ * their addresses coalesced back into rectangular ranges. Only constraint types Univer understands
+ * are emitted; a validation with no usable constraint is skipped. Returns an empty array when the
+ * sheet has none.
+ */
+function readDataValidations(ws: ExcelJS.Worksheet, sheetId: string): DataValidationRule[] {
+ const model = (ws.dataValidations as { model?: Record<string, ExcelJS.DataValidation | undefined> } | undefined)?.model;
+ /* v8 ignore next -- defensive: exceljs always exposes a (possibly empty) dataValidations model */
+ if (!model) return [];
+
+ // Group cells by an identical validation config; the key is order-stable across the sheet.
+ const groups = new Map<string, { config: ExcelJS.DataValidation; cells: CellRef[] }>();
+ for (const [address, config] of Object.entries(model)) {
+ /* v8 ignore next -- defensive: exceljs model entries always carry a type */
+ if (!config?.type) continue;
+ const cell = parseAddress(address);
+ /* v8 ignore next -- defensive: exceljs validation keys are always well-formed addresses */
+ if (!cell) continue;
+ const key = JSON.stringify([config.type, config.operator ?? null, config.formulae ?? null]);
+ const group = groups.get(key) ?? { config, cells: [] };
+ group.cells.push({ row: cell.row, column: cell.col });
+ groups.set(key, group);
+ }
+
+ const rules: DataValidationRule[] = [];
+ let index = 0;
+ for (const { config, cells } of groups.values()) {
+ const rule = buildValidationRule(config, coalesceRanges(cells), `dv-${sheetId}-${index}`);
+ if (rule) {
+ rules.push(rule);
+ index++;
+ }
+ }
+ return rules;
+}
+
+/**
+ * Translates one exceljs validation config into a Univer rule, or null when its constraint can't be
+ * represented (an empty list). exceljs's type/operator strings already match Univer's enums; a
+ * `list`'s inline options are JSON-encoded the way Univer's list validator expects, while numeric,
+ * date, text-length and custom constraints carry their formula bounds and operator verbatim.
+ */
+function buildValidationRule(config: ExcelJS.DataValidation, ranges: IRange[], uid: string): DataValidationRule | null {
+ const rule: DataValidationRule = { uid, type: config.type, ranges };
+
+ if (config.type === "list") {
+ const raw = config.formulae?.[0];
+ if (raw == null) return null;
+ const inline = parseInlineListOptions(String(raw));
+ // An inline list ("a,b,c") becomes a JSON option array; a range reference ($A$1:$A$3) is
+ // passed through as the formula, which Univer resolves the same way.
+ rule.formula1 = inline ? JSON.stringify(inline) : String(raw);
+ return rule;
+ }
+
+ /* v8 ignore next -- defensive: exceljs's DataValidation.formulae is always an array */
+ const [formula1, formula2] = config.formulae ?? [];
+ if (formula1 != null) rule.formula1 = String(formula1);
+ if (formula2 != null) rule.formula2 = String(formula2);
+ if (config.operator) rule.operator = config.operator;
+ return rule;
+}
+
+/**
+ * Parses Excel's inline list syntax — a single comma-separated string wrapped in double quotes,
+ * e.g. `"a,b,c"` — into its option array. Returns null when the formula isn't an inline list (a
+ * range/name reference) so the caller can pass it through as a formula instead. Empty options are
+ * dropped, matching Univer's `serializeListOptions`.
+ */
+function parseInlineListOptions(formula: string): string[] | null {
+ if (formula.length < 2 || !formula.startsWith("\"") || !formula.endsWith("\"")) return null;
+ // Excel does not trim whitespace inside an inline list, so options are split verbatim.
+ return formula.slice(1, -1).split(",").filter((option) => option.length > 0);
+}
+
+/**
+ * Merges a set of cells into a minimal-ish list of rectangular ranges with a greedy sweep: each
+ * unclaimed cell grows right as far as contiguous cells allow, then down as many full-width rows as
+ * possible. A solid block collapses to a single range; scattered cells stay separate.
+ */
+function coalesceRanges(cells: CellRef[]): IRange[] {
+ const present = new Set(cells.map((c) => cellKey(c.row, c.column)));
+ const claimed = new Set<string>();
+ const ranges: IRange[] = [];
+
+ const sorted = [...cells].sort((a, b) => a.row - b.row || a.column - b.column);
+ for (const { row, column } of sorted) {
+ if (claimed.has(cellKey(row, column))) continue;
+
+ let endColumn = column;
+ while (present.has(cellKey(row, endColumn + 1)) && !claimed.has(cellKey(row, endColumn + 1))) endColumn++;
+
+ let endRow = row;
+ while (rowSpanFree(present, claimed, endRow + 1, column, endColumn)) endRow++;
+
+ for (let r = row; r <= endRow; r++) {
+ for (let c = column; c <= endColumn; c++) claimed.add(cellKey(r, c));
+ }
+ ranges.push({ startRow: row, endRow, startColumn: column, endColumn });
+ }
+ return ranges;
+}
+
+/** True when every cell of `row` across `[startColumn, endColumn]` is present and unclaimed. */
+function rowSpanFree(present: Set<string>, claimed: Set<string>, row: number, startColumn: number, endColumn: number): boolean {
+ for (let c = startColumn; c <= endColumn; c++) {
+ if (!present.has(cellKey(row, c)) || claimed.has(cellKey(row, c))) return false;
+ }
+ return true;
+}
+
+function cellKey(row: number, column: number): string {
+ return `${row},${column}`;
+}
+
+// #endregion
+
function readCells(ws: ExcelJS.Worksheet): Record<number, Record<number, ICellData>> {
const cellData: Record<number, Record<number, ICellData>> = {};
diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.ts
index b50e919e98..30d9f3e5a5 100644
--- a/packages/commons/src/lib/spreadsheet/workbook_model.ts
+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts
@@ -311,6 +311,26 @@ export function isFiniteNumber(v: unknown): v is number {
/** Univer stores floating sheet images (drawings) under this workbook resource. */
export const SHEET_DRAWING_RESOURCE = "SHEET_DRAWING_PLUGIN";
+/** Univer stores per-sheet data-validation rules (dropdowns, numeric/date constraints) here. */
+export const SHEET_DATA_VALIDATION_RESOURCE = "SHEET_DATA_VALIDATION_PLUGIN";
+
+/**
+ * A Univer data-validation rule. Matches `IDataValidationRule` from `@univerjs/core` (the subset the
+ * XLSX importer emits). For a `list` dropdown, `formula1` is the JSON-encoded option array that
+ * Univer's list validator parses via `deserializeListOptions`; for numeric/date constraints,
+ * `formula1`/`formula2` are the bound values and `operator` selects the comparison.
+ */
+export interface DataValidationRule {
+ uid: string;
+ /** Univer's `DataValidationType` string (e.g. "list", "whole", "decimal", "date", "custom"). */
+ type: string;
+ /** Univer's `DataValidationOperator` string, for numeric/date/text-length constraints. */
+ operator?: string;
+ formula1?: string;
+ formula2?: string;
+ ranges: IRange[];
+}
+
/**
* Extracts the floating drawings for one sheet from the `SHEET_DRAWING_PLUGIN` resource, in
* their stored z-order. The resource `data` is itself a JSON string keyed by sheet id: