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
fix(spreadsheet): export data validation back to XLSX
Elian Dorana8555d56acf6
diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.tsindex c1f1829a6c..4acdfa56a9 100644--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts@@ -569,7 +569,8 @@ describe("renderSpreadsheetToXlsx", () => {const dv = ws?.getCell("B2").dataValidation;expect(dv?.type).toBe("whole");expect(dv?.operator).toBe("between");- expect(dv?.formulae).toEqual(["1", "10"]);+ // exceljs coerces the numeric formula text back to numbers on read.+ expect(dv?.formulae).toEqual([1, 10]);});it("passes a range-referenced list through as a formula, not an inline list", async () => {@@ -606,6 +607,33 @@ describe("renderSpreadsheetToXlsx", () => {expect(ws?.getCell("E3").dataValidation).toBeUndefined();});+ it("writes a custom-formula validation (a formula, no operator)", async () => {+ const ws = (await roundTrip(validationWorkbook([+ {+ uid: "dv1",+ type: "custom",+ formula1: "=B2>0",+ ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }]+ }+ ]))).getWorksheet("Sheet1");++ const dv = ws?.getCell("B2").dataValidation;+ expect(dv?.type).toBe("custom");+ expect(dv?.formulae).toEqual(["=B2>0"]);+ expect(dv?.operator).toBeUndefined();+ });++ it("skips a list validation that has no options", async () => {+ const ws = (await roundTrip(validationWorkbook([+ {+ uid: "dv1",+ type: "list",+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]+ }+ ]))).getWorksheet("Sheet1");+ expect(ws?.getCell("A1").dataValidation).toBeUndefined();+ });+it("skips a validation type Excel cannot represent", async () => {const ws = (await roundTrip(validationWorkbook([{diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.tsindex c990b5e53a..4a3a14a7bf 100644--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts@@ -3,7 +3,8 @@** Unlike the HTML renderer, this is a near-lossless mapping: Univer's cell model mirrors* OOXML, so number formats pass through verbatim, the border-style enum maps almost 1:1 to- * Excel's, and fonts/fills/alignment/merges map directly. The heavy lifting (zip + XML) is+ * Excel's, and fonts/fills/alignment/merges map directly. Data-validation rules (dropdown lists,+ * numeric/date/text bounds) invert their import counterparts. The heavy lifting (zip + XML) is* delegated to `exceljs`.** The workbook type subset, sheet selection, and style resolution live in the shared@@ -256,6 +257,88 @@ function toFinite(value: number | undefined): number {// #endregion+// #region Data validation++/**+ * Writes a sheet's Univer data-validation rules (from the SHEET_DATA_VALIDATION_PLUGIN resource)+ * into the worksheet — the inverse of the importer's `readDataValidations`. Each rule is applied+ * once per range, because exceljs rejects a multi-range `sqref` on write; contiguous cells are+ * re-consolidated by exceljs when it serialises. Rules whose type Excel can't represent are skipped.+ */+function applyDataValidations(ws: ExcelJS.Worksheet, workbook: IWorkbookData, sheetId: string): void {+ for (const rule of getDataValidations(workbook, sheetId)) {+ const validation = buildExcelValidation(rule);+ /* v8 ignore next -- defensive: an imported rule always carries at least one range */+ if (!validation || !rule.ranges) continue;+ for (const range of rule.ranges) {+ ws.dataValidations.add(rangeToA1(range), validation);+ }+ }+}++/** exceljs's supported data-validation types; Univer types outside this set can't be exported. */+const EXCEL_VALIDATION_TYPES: ReadonlySet<string> = new Set(["list", "whole", "decimal", "date", "textLength", "custom"]);++/**+ * Converts a Univer rule to an exceljs `DataValidation`, or null when it can't be represented: a+ * type with no Excel equivalent (checkbox, none, time), or a list with no options. A `list`/+ * `listMultiple` becomes an Excel `list`: literal options (a JSON array in `formula1`) are re-joined+ * into Excel's inline `"a,b,c"` syntax, while a range/name reference is passed through as the+ * formula. Other types carry their bounds and operator verbatim.+ */+function buildExcelValidation(rule: DataValidationRule): ExcelJS.DataValidation | null {+ if (rule.type === "list" || rule.type === "listMultiple") {+ const options = parseListOptions(rule.formula1);+ if (options) return { type: "list", allowBlank: true, formulae: [`"${options.join(",")}"`] };+ // A range/name reference passes through; an absent/empty formula has no dropdown to write.+ if (rule.formula1) return { type: "list", allowBlank: true, formulae: [rule.formula1] };+ return null;+ }++ if (!EXCEL_VALIDATION_TYPES.has(rule.type)) return null;++ const formulae = [rule.formula1, rule.formula2].filter((f): f is string => f != null);+ const validation = { type: rule.type, allowBlank: true, formulae } as ExcelJS.DataValidation;+ if (rule.operator) validation.operator = rule.operator as ExcelJS.DataValidationOperator;+ return validation;+}++/**+ * Reads a Univer list `formula1` back into its literal options: a JSON-encoded string array (how+ * the list validator serialises inline options). Returns null when `formula1` is a range/name+ * reference (not a JSON array), so the caller passes it through as a formula instead.+ */+function parseListOptions(formula1: string | undefined): string[] | null {+ if (formula1 == null) return null;+ try {+ const parsed: unknown = JSON.parse(formula1);+ if (Array.isArray(parsed) && parsed.every((o) => typeof o === "string")) return parsed;+ } catch {+ // Not JSON — a range/name reference; fall through.+ }+ return null;+}++/** Converts a 0-based inclusive Univer range to an A1 sqref ("D2" for a single cell, else "D2:E3"). */+function rangeToA1(range: IRange): string {+ const start = `${columnLetters(range.startColumn)}${range.startRow + 1}`;+ if (range.startRow === range.endRow && range.startColumn === range.endColumn) return start;+ return `${start}:${columnLetters(range.endColumn)}${range.endRow + 1}`;+}++/** 0-based column index to its Excel letters (0 -> "A", 25 -> "Z", 26 -> "AA"). */+function columnLetters(index: number): string {+ let n = index;+ let letters = "";+ do {+ letters = String.fromCharCode(65 + (n % 26)) + letters;+ n = Math.floor(n / 26) - 1;+ } while (n >= 0);+ return letters;+}++// #endregion+function applyColumns(ws: ExcelJS.Worksheet, sheet: IWorksheetData): void {const columnData = sheet.columnData ?? {};for (const colStr of Object.keys(columnData)) {