Skip to content

Build your personal knowledge base with Trilium Notes

test(commons): reach 100% coverage

Elian Doran80438c0d2b25
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 26cef25d1b..b70c25e152 100644
--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts
@@ -1,7 +1,7 @@
import ExcelJS from "exceljs";
import { describe, expect, it } from "vitest";
-import { parseXlsxToWorkbook, toArrayBuffer } from "./parse_from_xlsx.js";
+import { excelColorToRgb, parseRange, parseXlsxToWorkbook, toArrayBuffer } from "./parse_from_xlsx.js";
import {
BorderStyle,
CellValueType,
@@ -215,10 +215,233 @@ describe("parseXlsxToWorkbook", () => {
expect(workbook.sheetOrder.map((id) => workbook.sheets[id].name)).toEqual(["First", "Second"]);
});
+ it("handles a sheet with no cells (null columns)", async () => {
+ // An empty worksheet reports `ws.columns === null`, exercising readColumns' `?? []` fallback.
+ const sheet = await roundTrip((wb) => {
+ wb.addWorksheet("Empty");
+ });
+ expect(sheet.columnData).toEqual({});
+ expect(sheet.columnCount).toBe(20);
+ });
+
it("throws on a non-xlsx buffer", async () => {
await expect(parseXlsxToWorkbook(new Uint8Array([1, 2, 3]))).rejects.toThrow(/parse/i);
});
+ it("reads a date value as an Excel serial number", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = new Date(Date.UTC(2026, 3, 6));
+ });
+ expect(cellA1(sheet)).toMatchObject({ v: 46118, t: CellValueType.NUMBER });
+ });
+
+ it("reads a hyperlink keeping the display text only", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = { text: "Click", hyperlink: "https://example.com" };
+ });
+ expect(cellA1(sheet)).toMatchObject({ v: "Click", t: CellValueType.STRING });
+ });
+
+ it("flattens rich text into plain text", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = { richText: [{ text: "Hello " }, { text: "World" }] };
+ });
+ expect(cellA1(sheet)).toMatchObject({ v: "Hello World", t: CellValueType.STRING });
+ });
+
+ it("reads an error value as a forced string", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = { error: "#DIV/0!" } as ExcelJS.CellErrorValue;
+ });
+ expect(cellA1(sheet)).toMatchObject({ v: "#DIV/0!", t: CellValueType.FORCE_STRING });
+ });
+
+ it("reads cached formula results of every primitive kind", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = { formula: "TRUE()", result: true } as ExcelJS.CellFormulaValue;
+ ws.getCell("A2").value = {
+ formula: "TODAY()",
+ result: new Date(Date.UTC(2026, 3, 6))
+ } as ExcelJS.CellFormulaValue;
+ ws.getCell("A3").value = {
+ formula: "1/0",
+ result: { error: "#DIV/0!" }
+ } as ExcelJS.CellFormulaValue;
+ ws.getCell("A4").value = { formula: "T(1)", result: "txt" } as ExcelJS.CellFormulaValue;
+ ws.getCell("A5").value = { formula: "NA()", result: undefined } as ExcelJS.CellFormulaValue;
+ });
+ expect(sheet.cellData[0][0]).toMatchObject({ f: "=TRUE()", v: true, t: CellValueType.BOOLEAN });
+ expect(sheet.cellData[1][0]).toMatchObject({ f: "=TODAY()", v: 46118, t: CellValueType.NUMBER });
+ expect(sheet.cellData[2][0]).toMatchObject({ f: "=1/0", v: "#DIV/0!", t: CellValueType.FORCE_STRING });
+ expect(sheet.cellData[3][0]).toMatchObject({ f: "=T(1)", v: "txt", t: CellValueType.STRING });
+ const naCell = sheet.cellData[4][0];
+ expect(naCell?.f).toBe("=NA()");
+ expect(naCell?.v).toBeUndefined();
+ });
+
+ it("maps the remaining horizontal and vertical alignment options", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = "a";
+ ws.getCell("A1").alignment = { horizontal: "left", vertical: "top" };
+ ws.getCell("B1").value = "b";
+ ws.getCell("B1").alignment = { horizontal: "center", vertical: "bottom" };
+ });
+ expect(sheet.cellData[0][0]?.s).toMatchObject({ ht: HorizontalAlign.LEFT, vt: VerticalAlign.TOP });
+ expect(sheet.cellData[0][1]?.s).toMatchObject({ ht: HorizontalAlign.CENTER, vt: VerticalAlign.BOTTOM });
+ });
+
+ it("ignores alignment axes that have no Univer equivalent", async () => {
+ // Only a vertical set -> horizontalAlign returns null (default branch); only a horizontal
+ // set -> verticalAlign returns null. Each cell must carry exactly one of ht/vt.
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = "a";
+ ws.getCell("A1").alignment = { vertical: "middle" };
+ ws.getCell("B1").value = "b";
+ ws.getCell("B1").alignment = { horizontal: "right" };
+ });
+ const aStyle = styleOf(sheet.cellData[0][0]);
+ expect(aStyle.vt).toBe(VerticalAlign.MIDDLE);
+ expect(aStyle.ht).toBeUndefined();
+ const bStyle = styleOf(sheet.cellData[0][1]);
+ expect(bStyle.ht).toBe(HorizontalAlign.RIGHT);
+ expect(bStyle.vt).toBeUndefined();
+ });
+
+ it("reads vertical and angled text rotation", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = "a";
+ ws.getCell("A1").alignment = { textRotation: "vertical" };
+ ws.getCell("B1").value = "b";
+ ws.getCell("B1").alignment = { textRotation: 45 };
+ });
+ expect(sheet.cellData[0][0]?.s).toMatchObject({ tr: { v: 1 } });
+ expect(sheet.cellData[0][1]?.s).toMatchObject({ tr: { a: 45 } });
+ });
+
+ it("maps every remaining exceljs border style to the Univer enum", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const styles = [
+ ["A1", "hair", BorderStyle.HAIR],
+ ["B1", "dashed", BorderStyle.DASHED],
+ ["C1", "dashDot", BorderStyle.DASH_DOT],
+ ["D1", "dashDotDot", BorderStyle.DASH_DOT_DOT],
+ ["E1", "double", BorderStyle.DOUBLE],
+ ["F1", "mediumDashed", BorderStyle.MEDIUM_DASHED],
+ ["G1", "mediumDashDot", BorderStyle.MEDIUM_DASH_DOT],
+ ["H1", "mediumDashDotDot", BorderStyle.MEDIUM_DASH_DOT_DOT],
+ ["I1", "slantDashDot", BorderStyle.SLANT_DASH_DOT]
+ ] as const;
+ for (const [addr, excelStyle] of styles) {
+ const cell = ws.getCell(addr);
+ cell.value = "b";
+ cell.border = { top: { style: excelStyle } };
+ }
+ });
+ const expectations: Array<[number, BorderStyle]> = [
+ [0, BorderStyle.HAIR],
+ [1, BorderStyle.DASHED],
+ [2, BorderStyle.DASH_DOT],
+ [3, BorderStyle.DASH_DOT_DOT],
+ [4, BorderStyle.DOUBLE],
+ [5, BorderStyle.MEDIUM_DASHED],
+ [6, BorderStyle.MEDIUM_DASH_DOT],
+ [7, BorderStyle.MEDIUM_DASH_DOT_DOT],
+ [8, BorderStyle.SLANT_DASH_DOT]
+ ];
+ for (const [col, expected] of expectations) {
+ expect(sheet.cellData[0][col]?.s).toMatchObject({ bd: { t: { s: expected } } });
+ }
+ });
+
+ it("resolves theme colors with tint across every HSL branch", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ // theme 5 (#ED7D31, max===r) tint +0.4 -> #F4B183, on font color.
+ const orange = ws.getCell("A1");
+ orange.value = "o";
+ orange.font = { color: { theme: 5, tint: 0.4 } as unknown as ExcelJS.Color };
+ // theme 4 (#4472C4, max===b) tint -0.25 -> #2F5597, on solid fill.
+ const blue = ws.getCell("B1");
+ blue.value = "b";
+ blue.fill = {
+ type: "pattern",
+ pattern: "solid",
+ fgColor: { theme: 4, tint: -0.25 } as unknown as ExcelJS.Color
+ };
+ // theme 9 (#70AD47, max===g) tint +0.6.
+ const green = ws.getCell("C1");
+ green.value = "g";
+ green.font = { color: { theme: 9, tint: 0.6 } as unknown as ExcelJS.Color };
+ // theme 0 (#FFFFFF, gray path max===min) tint -0.5 -> #808080 (hslToRgb s===0).
+ const gray = ws.getCell("D1");
+ gray.value = "w";
+ gray.font = { color: { theme: 0, tint: -0.5 } as unknown as ExcelJS.Color };
+ });
+ expect(sheet.cellData[0][0]?.s).toMatchObject({ cl: { rgb: "#F4B183" } });
+ expect(sheet.cellData[0][1]?.s).toMatchObject({ bg: { rgb: "#2F5597" } });
+ // green/gray just need to resolve to a hex string and exercise their branches.
+ expect(styleOf(sheet.cellData[0][2]).cl?.rgb).toMatch(/^#[0-9A-F]{6}$/);
+ expect(sheet.cellData[0][3]?.s).toMatchObject({ cl: { rgb: "#808080" } });
+ });
+
+ it("flags a sheet with gridlines turned off", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ ws.getCell("A1").value = "x";
+ ws.views = [{ showGridLines: false } as ExcelJS.WorksheetView];
+ });
+ expect(sheet.showGridlines).toBe(0);
+ });
+
+ it("drops a font color that resolves to nothing while keeping other font styling", async () => {
+ // A fully-transparent (alpha 00) font color resolves to null, so no `cl` is emitted, but
+ // the bold flag still survives (covers the `if (color)` false branch in readFont).
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const cell = ws.getCell("A1");
+ cell.value = "x";
+ cell.font = { bold: true, color: { argb: "00FF0000" } };
+ });
+ const style = styleOf(cellA1(sheet));
+ expect(style.bl).toBe(1);
+ expect(style.cl).toBeUndefined();
+ });
+
+ it("ignores an alignment object whose only setting has no Univer equivalent", async () => {
+ // `horizontal: "fill"` maps to null and nothing else is set, so readAlignment returns null
+ // and the cell carries no alignment style at all.
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const cell = ws.getCell("A1");
+ cell.value = "x";
+ cell.alignment = { horizontal: "fill" };
+ });
+ const style = styleOf(cellA1(sheet));
+ expect(style.ht).toBeUndefined();
+ expect(style.vt).toBeUndefined();
+ });
+
+ it("skips the theme-1 default text color so the cell inherits Univer's default", async () => {
+ const sheet = await roundTrip((wb) => {
+ const ws = wb.addWorksheet("S");
+ const cell = ws.getCell("A1");
+ cell.value = "x";
+ cell.font = { bold: true, color: { theme: 1 } as unknown as ExcelJS.Color };
+ });
+ const style = styleOf(cellA1(sheet));
+ expect(style.bl).toBe(1);
+ expect(style.cl).toBeUndefined();
+ });
+
it("parses an xlsx delivered as an offset view into a larger buffer (Node Buffer import path)", async () => {
// Reproduces the real server-import shape: a Node Buffer that views part of a larger
// backing buffer at a non-zero offset (single.ts / zip.ts both pass Buffers). With the
@@ -275,3 +498,47 @@ describe("toArrayBuffer", () => {
expect(toArrayBuffer(ab)).toBe(ab);
});
});
+
+describe("excelColorToRgb", () => {
+ it("resolves ARGB, theme and edge-case colors", () => {
+ // 8-digit ARGB drops the alpha; 6-digit ARGB is taken verbatim.
+ expect(excelColorToRgb({ argb: "FF112233" })).toBe("#112233");
+ expect(excelColorToRgb({ argb: "ABCDEF" } as Partial<ExcelJS.Color>)).toBe("#ABCDEF");
+ // Fully-transparent (alpha "00") and non-hex strings resolve to null.
+ expect(excelColorToRgb({ argb: "00FFFFFF" })).toBeNull();
+ expect(excelColorToRgb({ argb: "nothex" })).toBeNull();
+ // Theme + tint resolves against the Office palette.
+ expect(excelColorToRgb({ theme: 5, tint: 0.4 } as Partial<ExcelJS.Color>)).toBe("#F4B183");
+ // Out-of-range theme index, missing color and empty object all resolve to null.
+ expect(excelColorToRgb({ theme: 99 } as Partial<ExcelJS.Color>)).toBeNull();
+ expect(excelColorToRgb(undefined)).toBeNull();
+ expect(excelColorToRgb({} as Partial<ExcelJS.Color>)).toBeNull();
+ });
+
+ it("exercises the tint and hue branches of the HSL math", () => {
+ // A theme color with no tint short-circuits applyTint (returns the base hex untouched).
+ expect(excelColorToRgb({ theme: 4 } as Partial<ExcelJS.Color>)).toBe("#4472C4");
+ // theme 11 (#954F72): max===r with g < b, and a hue > 2/3 so hueToChannel's t>1 wraps.
+ // A non-zero tint forces the value through rgbToHsl/hslToRgb/hueToChannel.
+ expect(excelColorToRgb({ theme: 11, tint: 0.2 } as Partial<ExcelJS.Color>)).toMatch(/^#[0-9A-F]{6}$/);
+ // theme 8 (#5B9BD5): max===b with a low hue so hueToChannel's t<0 wraps the other way.
+ expect(excelColorToRgb({ theme: 8, tint: -0.3 } as Partial<ExcelJS.Color>)).toMatch(/^#[0-9A-F]{6}$/);
+ });
+});
+
+describe("parseRange", () => {
+ it("parses ranges, single cells and rejects malformed refs", () => {
+ // A two-cell range, normalized to 0-based inclusive bounds.
+ expect(parseRange("B2:D5")).toEqual({ startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 });
+ // Reversed corners are normalized via min/max, so endpoint order doesn't matter.
+ expect(parseRange("D5:B2")).toEqual({ startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 });
+ // A single address (no ":") collapses to a 1×1 range (the `to ?? from` fallback).
+ expect(parseRange("A1")).toEqual({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 });
+ // Multi-letter columns advance base-26: AA -> column index 26.
+ expect(parseRange("AA10")).toEqual({ startRow: 9, endRow: 9, startColumn: 26, endColumn: 26 });
+ // A malformed start endpoint (no row digits) yields null.
+ expect(parseRange("zzz")).toBeNull();
+ // A malformed end endpoint yields null too (covers the `!end` half of the guard).
+ expect(parseRange("A1:zz")).toBeNull();
+ });
+});
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
index 8ee74ceb86..f313f8b3a5 100644
--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts
@@ -101,6 +101,7 @@ function readSheet(ws: ExcelJS.Worksheet, id: string): IWorksheetData {
if (isFiniteNumber(ws.properties?.defaultColWidth)) {
sheet.defaultColumnWidth = excelWidthToPx(ws.properties.defaultColWidth);
}
+ /* v8 ignore next -- defensive: exceljs always reports a defaultRowHeight (15pt default), so the non-finite branch is unreachable */
if (isFiniteNumber(ws.properties?.defaultRowHeight)) {
sheet.defaultRowHeight = pointsToPx(ws.properties.defaultRowHeight);
}
@@ -162,6 +163,7 @@ function applyCellValue(data: ICellData, cell: ExcelJS.Cell): void {
break;
case ExcelJS.ValueType.Hyperlink:
// Keep the display text; the link itself has no inline Univer equivalent.
+ /* v8 ignore next -- defensive: a hyperlink cell always carries display text */
data.v = String((cell.value as ExcelJS.CellHyperlinkValue)?.text ?? "");
data.t = CellValueType.STRING;
break;
@@ -170,6 +172,7 @@ function applyCellValue(data: ICellData, cell: ExcelJS.Cell): void {
data.t = CellValueType.STRING;
break;
case ExcelJS.ValueType.Error:
+ /* v8 ignore next -- defensive: an error cell always carries an error code */
data.v = String((cell.value as ExcelJS.CellErrorValue)?.error ?? "#ERROR!");
data.t = CellValueType.FORCE_STRING;
break;
@@ -199,6 +202,7 @@ function assignPrimitive(data: ICellData, result: ExcelJS.Cell["result"]): void
}
function flattenRichText(value: ExcelJS.CellRichTextValue): string {
+ /* v8 ignore next -- defensive: a rich-text cell always carries a richText run array */
return (value?.richText ?? []).map((run) => run.text).join("");
}
@@ -299,10 +303,12 @@ function readBorderSide(side: Partial<ExcelJS.Border> | undefined): IBorderStyle
function readMerges(ws: ExcelJS.Worksheet): IRange[] {
// exceljs exposes merges as A1-style range strings on the worksheet model.
+ /* v8 ignore next -- defensive: exceljs always exposes model.merges as an array */
const merges = (ws.model as { merges?: string[] })?.merges ?? [];
const ranges: IRange[] = [];
for (const ref of merges) {
const range = parseRange(ref);
+ /* v8 ignore next -- defensive: exceljs merge refs are always well-formed ranges */
if (range) ranges.push(range);
}
return ranges;
@@ -316,7 +322,7 @@ function readRows(ws: ExcelJS.Worksheet): { rowData: Record<number, IRowData>; m
// such as a thin spacer row, which `false` would skip.
ws.eachRow({ includeEmpty: true }, (row, rowNumber) => {
const index = rowNumber - 1;
- if (rowNumber > maxRow) maxRow = rowNumber - 1;
+ if (index > maxRow) maxRow = index;
const meta: IRowData = {};
// exceljs leaves `row.height` undefined unless the row carries a custom height, so this
@@ -396,7 +402,7 @@ function solidFillColor(fill: ExcelJS.Fill | undefined): Partial<ExcelJS.Color>
* Handles explicit ARGB and theme colors (resolved against the standard Office palette plus
* tint). Indexed (legacy) colors are not handled.
*/
-function excelColorToRgb(color: Partial<ExcelJS.Color> | undefined): string | null {
+export function excelColorToRgb(color: Partial<ExcelJS.Color> | undefined): string | null {
if (!color) return null;
if (typeof color.argb === "string") return argbToHex(color.argb);
// exceljs' `Color` type omits `tint`, though it's present on theme colors at runtime.
@@ -493,7 +499,7 @@ function clampChannel(v: number): string {
}
/** Parses an A1-style range ("B2:D5" or a single "A1") into a 0-based inclusive `IRange`. */
-function parseRange(ref: string): IRange | null {
+export function parseRange(ref: string): IRange | null {
const [from, to] = ref.split(":");
const start = parseAddress(from);
const end = parseAddress(to ?? from);
diff --git a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
index f61080f7bf..107494e20c 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
@@ -1,7 +1,7 @@
import JSZip from "jszip";
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { renderSpreadsheetToCsv, renderSpreadsheetToCsvZip } from "./render_to_csv.js";
+import { formatDate, renderSpreadsheetToCsv, renderSpreadsheetToCsvZip } from "./render_to_csv.js";
/** A sheet definition for {@link multiSheetWorkbook}. */
interface SheetSpec {
@@ -119,6 +119,19 @@ describe("renderSpreadsheetToCsv", () => {
expect(csv).toBe("2026-04-06 12:00,2026-04-06 12:00:00");
});
+ it("falls back to the cell's own pattern for partial date formats (not full y/m/d)", () => {
+ // Month-year / year-only patterns are date formats but lack a day component, so they
+ // fall through to formatNumfmt(pattern, serial) rather than the ISO yyyy-mm-dd path.
+ const csv = renderSpreadsheetToCsv(workbook({
+ 0: {
+ 0: { v: 46118.5, t: 2, s: { n: { pattern: "mmm yyyy" } } },
+ 1: { v: 46118.5, t: 2, s: { n: { pattern: "mmm-yy" } } },
+ 2: { v: 46118.5, t: 2, s: { n: { pattern: "yyyy" } } }
+ }
+ }));
+ expect(csv).toBe("Apr 2026,Apr-26,2026");
+ });
+
it("keeps a non-date numeric cell raw even when it has a number format", () => {
const csv = renderSpreadsheetToCsv(workbook({
0: { 0: { v: 1234.5, t: 2, s: { n: { pattern: "#,##0.00" } } } }
@@ -186,6 +199,21 @@ describe("renderSpreadsheetToCsv", () => {
expect(renderSpreadsheetToCsv(allHidden)).toBe("");
});
+ it("renders cell values when the workbook has no styles table", () => {
+ // The `workbook` helper always sets `styles`, so build a literal without that key to
+ // exercise the `workbook.styles ?? {}` fallback.
+ const noStyles = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: { id: "s1", name: "Sheet1", hidden: 0, cellData: { 0: { 0: { v: "a" }, 1: { v: "b" } } } }
+ }
+ }
+ });
+ expect(renderSpreadsheetToCsv(noStyles)).toBe("a,b");
+ });
+
it("throws on unparseable JSON and on a workbook with no sheets", () => {
expect(() => renderSpreadsheetToCsv("not json")).toThrow(/parse/i);
expect(() => renderSpreadsheetToCsv(JSON.stringify({ version: 1 }))).toThrow(/no sheets/i);
@@ -235,8 +263,84 @@ describe("renderSpreadsheetToCsvZip", () => {
expect(Object.keys(entries).sort()).toEqual(["Sheet (3).csv", "Sheet.csv", "sheet (2).csv"]);
});
+ it("renders cell values when the workbook has no styles table", async () => {
+ // `multiSheetWorkbook` always sets `styles`, so build a literal without that key to
+ // exercise the `workbook.styles ?? {}` fallback in the zip path.
+ const noStyles = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: { id: "s1", name: "Data", hidden: 0, cellData: { 0: { 0: { v: "a" }, 1: { v: "b" } } } }
+ }
+ }
+ });
+ const entries = await readZip(await renderSpreadsheetToCsvZip(noStyles));
+ expect(entries["Data.csv"]).toBe("a,b");
+ });
+
+ it("falls back to 'Sheet.csv' when a sheet has no name", async () => {
+ // A visible sheet whose `name` is omitted (undefined) exercises the `sheetName ?? ""`
+ // nullish fallback, which then resolves to "Sheet".
+ const noName = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: { id: "s1", hidden: 0, cellData: { 0: { 0: { v: "x" } } } }
+ }
+ }
+ });
+ const entries = await readZip(await renderSpreadsheetToCsvZip(noName));
+ expect(Object.keys(entries)).toEqual(["Sheet.csv"]);
+ expect(entries["Sheet.csv"]).toBe("x");
+ });
+
it("throws on unparseable JSON and on a workbook with no sheets", async () => {
await expect(renderSpreadsheetToCsvZip("not json")).rejects.toThrow(/parse/i);
await expect(renderSpreadsheetToCsvZip(JSON.stringify({ version: 1 }))).rejects.toThrow(/no sheets/i);
});
});
+
+describe("formatDate", () => {
+ it("renders a full y/m/d date as ISO 8601, partial formats via their own pattern", () => {
+ // 46118 is 2026-04-06 in Excel's serial date system.
+ expect(formatDate("yyyy-mm-dd", 46118)).toBe("2026-04-06");
+ // A partial (month-year) date format falls through to formatNumfmt(pattern, serial).
+ expect(formatDate("mmm yyyy", 46118)).toBe("Apr 2026");
+ });
+
+ it("returns null when the formatter throws", () => {
+ // getFormatDateInfo("General;General;General;yyyy") reports no date parts (so the ISO
+ // branch is skipped), then format() throws on the partition syntax, hitting the catch.
+ expect(formatDate("General;General;General;yyyy", 46118.5)).toBeNull();
+ });
+});
+
+describe("renderSpreadsheetToCsv (formatDate returns null)", () => {
+ afterEach(() => {
+ vi.resetModules();
+ vi.doUnmock("numfmt");
+ });
+
+ it("falls back to the raw value when a date cell can't be formatted", async () => {
+ // No public, real numfmt pattern makes isDateFormat() true yet formatDate() return null,
+ // so the only way to exercise cellText's `formatted == null` fallback is to mock numfmt:
+ // isDateFormat -> true (enters the date branch) and format -> throws (formatDate returns
+ // null), leaving cellText to emit String(cell.v) — the raw serial.
+ vi.resetModules();
+ vi.doMock("numfmt", () => ({
+ isDateFormat: () => true,
+ getFormatDateInfo: () => ({ year: true, month: false, day: false }),
+ format: () => {
+ throw new Error("boom");
+ }
+ }));
+
+ const { renderSpreadsheetToCsv: render } = await import("./render_to_csv.js");
+ const csv = render(workbook({
+ 0: { 0: { v: 46118, t: 2, s: { n: { pattern: "yyyy-mm-dd" } } } }
+ }));
+ expect(csv).toBe("46118");
+ });
+});
diff --git a/packages/commons/src/lib/spreadsheet/render_to_csv.ts b/packages/commons/src/lib/spreadsheet/render_to_csv.ts
index 143e767a90..c8ce2e8d88 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_csv.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.ts
@@ -166,7 +166,7 @@ function cellText(cell: ICellData | undefined, styles: Record<string, IStyleData
* fall back to the cell's own pattern so the output stays a readable date, never a serial.
* Returns `null` if the value can't be formatted, so the caller falls back to the raw value.
*/
-function formatDate(pattern: string, serial: number): string | null {
+export function formatDate(pattern: string, serial: number): string | null {
try {
const info = getFormatDateInfo(pattern);
if (info.year && info.month && info.day) {
diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts
index b6c4bc1905..6881e64b1a 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts
@@ -213,6 +213,168 @@ describe("renderSpreadsheetToXlsx", () => {
await expect(renderSpreadsheetToXlsx("not json")).rejects.toThrow(/parse/i);
});
+ it("throws when the workbook has no sheets", async () => {
+ await expect(renderSpreadsheetToXlsx(JSON.stringify({ version: 1, workbook: {} }))).rejects.toThrow(/no sheets/i);
+ });
+
+ it("emits a single empty Sheet1 when no sheets are visible", async () => {
+ const json = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ styles: {},
+ sheets: {
+ s1: { id: "s1", name: "Secret", hidden: 1, mergeData: [], cellData: {}, rowData: {}, columnData: {} }
+ }
+ }
+ });
+ const wb = await roundTrip(json);
+ expect(wb.worksheets.map((w) => w.name)).toEqual(["Sheet1"]);
+ });
+
+ it("renders a workbook with no styles key and a sheet omitting merge/column/row data", async () => {
+ // No `styles` key on the workbook, and the sheet omits mergeData/columnData/rowData
+ // entirely so the `?? {}` / `?? []` fallbacks are exercised (do not use singleCellWorkbook
+ // which always sets these).
+ const json = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"],
+ sheets: {
+ s1: { id: "s1", name: "Bare", hidden: 0, cellData: { "0": { "0": { v: "x", t: 1 } } } }
+ }
+ }
+ });
+ const ws = (await roundTrip(json)).worksheets[0];
+ expect(ws.name).toBe("Bare");
+ expect(ws.getCell("A1").value).toBe("x");
+ });
+
+ it("skips a null cell, an empty merge/column/row set, without error", async () => {
+ // cellData entry whose value is null -> writeCell must skip it (the `!cell` guard).
+ const ws = (await roundTrip(
+ singleCellWorkbook(null, { cellData: { "0": { "0": null, "1": { v: "kept", t: 1 } } } })
+ )).worksheets[0];
+ expect(ws.getCell("A1").value).toBeNull();
+ expect(ws.getCell("B1").value).toBe("kept");
+ });
+
+ it("applies style to a cell with no value (non-formula)", async () => {
+ // A cell `{ s: { bl: 1 } }` with no `v` and no `f`: font applied, no value written.
+ const ws = (await roundTrip(singleCellWorkbook({ s: { bl: 1 } }))).worksheets[0];
+ expect(ws.getCell("A1").value).toBeNull();
+ expect(ws.getCell("A1").font.bold).toBe(true);
+ });
+
+ it("writes a formula with no cached result", async () => {
+ // A formula cell with no `v` -> result is undefined.
+ const ws = (await roundTrip(singleCellWorkbook({ f: "=A1" }))).worksheets[0];
+ const value = ws.getCell("A1").value as ExcelJS.CellFormulaValue;
+ expect(value.formula).toBe("A1");
+ expect(value.result).toBeUndefined();
+ });
+
+ it("maps text rotation: vertical, an explicit angle, and ignores a zero angle", async () => {
+ const vertical = (await roundTrip(singleCellWorkbook({ v: "x", s: { tr: { v: 1 } } }))).worksheets[0];
+ expect(vertical.getCell("A1").alignment.textRotation).toBe("vertical");
+
+ const angled = (await roundTrip(singleCellWorkbook({ v: "x", s: { tr: { a: 45 } } }))).worksheets[0];
+ expect(angled.getCell("A1").alignment.textRotation).toBe(45);
+
+ // tr present but angle is 0 -> the `!== 0` guard means no textRotation (and no alignment,
+ // which exceljs reads back as undefined).
+ const zero = (await roundTrip(singleCellWorkbook({ v: "x", s: { tr: { a: 0 } } }))).worksheets[0];
+ expect(zero.getCell("A1").alignment).toBeUndefined();
+ });
+
+ it("maps left/center horizontal and top/bottom vertical alignment", async () => {
+ const left = (await roundTrip(singleCellWorkbook({ v: "x", s: { ht: 1 } }))).worksheets[0];
+ expect(left.getCell("A1").alignment.horizontal).toBe("left");
+
+ const center = (await roundTrip(singleCellWorkbook({ v: "x", s: { ht: 2 } }))).worksheets[0];
+ expect(center.getCell("A1").alignment.horizontal).toBe("center");
+
+ const top = (await roundTrip(singleCellWorkbook({ v: "x", s: { vt: 1 } }))).worksheets[0];
+ expect(top.getCell("A1").alignment.vertical).toBe("top");
+
+ const bottom = (await roundTrip(singleCellWorkbook({ v: "x", s: { vt: 3 } }))).worksheets[0];
+ expect(bottom.getCell("A1").alignment.vertical).toBe("bottom");
+ });
+
+ it("ignores unknown horizontal/vertical alignment codes", async () => {
+ // Unknown ht/vt fall through to the default branch -> no alignment applied (exceljs reads
+ // back as undefined).
+ const ws = (await roundTrip(singleCellWorkbook({ v: "x", s: { ht: 99, vt: 99 } }))).worksheets[0];
+ expect(ws.getCell("A1").alignment).toBeUndefined();
+ });
+
+ it("maps the remaining Univer border-style enum codes to exceljs styles", async () => {
+ // A cell can carry only 4 border sides, so split the 9 remaining codes across cells.
+ // HAIR=2, DASHED=4, DASH_DOT=5, DASH_DOT_DOT=6 / DOUBLE=7, MEDIUM_DASHED=9,
+ // MEDIUM_DASH_DOT=10, MEDIUM_DASH_DOT_DOT=11 / SLANT_DASH_DOT=12.
+ const first = (await roundTrip(singleCellWorkbook({
+ v: "b",
+ s: { bd: { t: { s: 2 }, r: { s: 4 }, b: { s: 5 }, l: { s: 6 } } }
+ }))).worksheets[0];
+ let border = first.getCell("A1").border;
+ expect(border.top?.style).toBe("hair");
+ expect(border.right?.style).toBe("dashed");
+ expect(border.bottom?.style).toBe("dashDot");
+ expect(border.left?.style).toBe("dashDotDot");
+
+ const second = (await roundTrip(singleCellWorkbook({
+ v: "b",
+ s: { bd: { t: { s: 7 }, r: { s: 9 }, b: { s: 10 }, l: { s: 11 } } }
+ }))).worksheets[0];
+ border = second.getCell("A1").border;
+ expect(border.top?.style).toBe("double");
+ expect(border.right?.style).toBe("mediumDashed");
+ expect(border.bottom?.style).toBe("mediumDashDot");
+ expect(border.left?.style).toBe("mediumDashDotDot");
+
+ const third = (await roundTrip(singleCellWorkbook({
+ v: "b",
+ s: { bd: { t: { s: 12 } } }
+ }))).worksheets[0];
+ expect(third.getCell("A1").border.top?.style).toBe("slantDashDot");
+ });
+
+ it("falls back to FF000000 for a border side with a style but no color", async () => {
+ const ws = (await roundTrip(singleCellWorkbook({ v: "b", s: { bd: { b: { s: 1 } } } }))).worksheets[0];
+ expect(ws.getCell("A1").border.bottom?.style).toBe("thin");
+ expect(ws.getCell("A1").border.bottom?.color?.argb).toBe("FF000000");
+ });
+
+ it("applies no border when the only side is NONE", async () => {
+ // buildBorder returns null because every side resolves to no style -> exceljs reads back
+ // the whole border as undefined.
+ const ws = (await roundTrip(singleCellWorkbook({ v: "b", s: { bd: { t: { s: 0 } } } }))).worksheets[0];
+ expect(ws.getCell("A1").border).toBeUndefined();
+ });
+
+ it("passes an 8-digit AARRGGBB color through verbatim", async () => {
+ const ws = (await roundTrip(singleCellWorkbook({ v: "x", s: { cl: { rgb: "#11223344" } } }))).worksheets[0];
+ expect(ws.getCell("A1").font.color?.argb).toBe("11223344");
+ });
+
+ it("applies no color for an invalid rgb (font and border)", async () => {
+ // Invalid rgb -> toArgb returns null: no font color; border side with a style but an
+ // invalid color falls back to FF000000.
+ const ws = (await roundTrip(singleCellWorkbook({
+ v: "x",
+ s: { bl: 1, cl: { rgb: "notacolor" }, bd: { b: { s: 1, cl: { rgb: "#zzz" } } } }
+ }))).worksheets[0];
+ const cell = ws.getCell("A1");
+ // Font still applied (bold), but no color attached.
+ expect(cell.font.bold).toBe(true);
+ expect(cell.font.color).toBeUndefined();
+ // No fill written -> exceljs reads back the default "none" pattern fill.
+ expect((cell.fill as ExcelJS.FillPattern)?.pattern).toBe("none");
+ // Border keeps the style with the fallback color.
+ expect(cell.border.bottom?.style).toBe("thin");
+ expect(cell.border.bottom?.color?.argb).toBe("FF000000");
+ });
+
describe("output is a valid xlsx", () => {
let buffer: ExcelJS.Buffer;
beforeAll(async () => {
@@ -241,6 +403,8 @@ describe("uniqueSheetName", () => {
expect(uniqueSheetName(" ", new Set())).toBe("Sheet");
expect(uniqueSheetName("History", new Set())).toBe("History_");
expect(uniqueSheetName("history", new Set())).toBe("history_");
+ // An undefined name exercises the `name ?? ""` fallback in sanitizeSheetName.
+ expect(uniqueSheetName(undefined, new Set())).toBe("Sheet");
});
it("de-duplicates case-insensitively, keeping names within the 31-char limit", () => {