Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/sheet-names-code-points.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"javascript-excel": patch
---

Sheet names are limited to 31 code points, as in Excel, instead of 31 UTF-16 units. `validateSheetName`, the writer and `sanitizeSheetName` now accept a name such as 30 letters plus an emoji (Excel for Mac accepts it), and `sanitizeSheetName` cuts long names to 31 code points without splitting a surrogate pair. `History` stays reserved in any case (Excel refuses it), and `sanitizeSheetName` turns it into `Sheet`.
4 changes: 2 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ export type ColumnWidth = number | { wch: number } | { wpx: number } | 'auto';

**Sheet names.** The writer throws `INVALID_SHEET_NAME` unless the name:

- is 1 to 31 characters long. Excel counts code points: it accepts 30 x's and πŸ˜€, which is 31 code points and 32 UTF-16 units *(confirmed in Excel for Mac, 2026-11-17; conformance.md, 17-workbook)*. The writer still counts UTF-16 units (`name.length`), so it rejects such a name although Excel accepts it;
- is 1 to 31 characters long. Excel counts code points: it accepts 30 x's and πŸ˜€, which is 31 code points and 32 UTF-16 units *(confirmed in Excel for Mac, 2026-11-17; conformance.md, 17-workbook)*. `validateSheetName`, the writer and `sanitizeSheetName` count code points too (from 2.0.0-beta.1; before, they counted UTF-16 units and rejected such names);
- contains none of `\ / ? * [ ] :`;
- does not start or end with an apostrophe `'`;
- is not `History`, which Excel reserves: renaming a tab to it gives "History is a reserve word" *(confirmed in Excel for Mac, 2026-11-17; conformance.md, 17-workbook)*. The check ignores case (`history`, `HISTORY`); only `History` itself was tried in Excel.
Expand Down Expand Up @@ -724,7 +724,7 @@ export function serialToDate(serial: number, opts?: { date1904?: boolean; dateZo
### 4.6 Names

```ts
/** Replaces forbidden characters with '_', trims apostrophes, truncates to 31, falls back to 'Sheet'. */
/** Replaces forbidden characters with '_', trims apostrophes, truncates to 31 code points (never splitting a surrogate pair), falls back to 'Sheet' (also for 'History'). */
export function sanitizeSheetName(name: string): string;
/** Returns null when valid, or the reason. */
export function validateSheetName(name: string): null | 'empty' | 'too-long' | 'forbidden-char' | 'apostrophe' | 'reserved';
Expand Down
23 changes: 14 additions & 9 deletions packages/javascript-excel/src/sheet-names.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/**
* Sheet-name rules (docs/api.md Β§3.3, Β§4.6).
*
* Excel rejects names that are empty, longer than 31 characters, contain any
* Excel rejects names that are empty, longer than 31 characters (code points,
* not UTF-16 units: 30 x's and an emoji are accepted), contain any
* of \ / ? * [ ] :, or start or end with an apostrophe. It reserves 'History'
* (Excel for Mac: "History is a reserve word"); the check here ignores case.
* Names are unique case-insensitively (checked by the writer).
Expand All @@ -12,11 +13,19 @@ export type SheetNameProblem = "empty" | "too-long" | "forbidden-char" | "apostr

const FORBIDDEN = /[\\/?*[\]:]/;
const FORBIDDEN_ALL = /[\\/?*[\]:]/g;
const MAX_LENGTH = 31;

/** Length in code points, as Excel counts sheet names (a surrogate pair is one). */
function codePoints(s: string): number {
let n = 0;
for (const _ of s) n++;
return n;
}

/** Returns null when `name` is a valid sheet name, or the reason it is not. */
export function validateSheetName(name: string): SheetNameProblem | null {
if (typeof name !== "string" || name.length === 0) return "empty";
if (name.length > 31) return "too-long";
if (codePoints(name) > MAX_LENGTH) return "too-long";
if (FORBIDDEN.test(name)) return "forbidden-char";
if (name.startsWith("'") || name.endsWith("'")) return "apostrophe";
if (name.toLowerCase() === "history") return "reserved";
Expand All @@ -26,15 +35,11 @@ export function validateSheetName(name: string): SheetNameProblem | null {
/**
* Makes any string a valid sheet name: forbidden characters become '_',
* leading and trailing apostrophes are removed, the result is cut to 31
* characters (without splitting a surrogate pair), and an empty or reserved
* result becomes 'Sheet'. Uniqueness is the caller's job.
* code points (never splitting a surrogate pair), and an empty or reserved
* result ('History' in any case) becomes 'Sheet'. Uniqueness is the caller's job.
*/
export function sanitizeSheetName(name: string): string {
let s = String(name ?? "").replace(FORBIDDEN_ALL, "_").replace(/^'+|'+$/g, "");
if (s.length > 31) {
s = s.slice(0, 31);
if (/[\uD800-\uDBFF]$/.test(s)) s = s.slice(0, 30);
s = s.replace(/'+$/, "");
}
if (codePoints(s) > MAX_LENGTH) s = Array.from(s).slice(0, MAX_LENGTH).join("").replace(/'+$/, "");
return s.length === 0 || s.toLowerCase() === "history" ? "Sheet" : s;
}
24 changes: 23 additions & 1 deletion packages/javascript-excel/test/write/writer-features.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,29 @@ describe("sheet names (Β§4.6)", () => {
expect(out[1]).toBe("quoted");
expect([out[2], out[3], out[6]]).toEqual(["Sheet", "Sheet", "Sheet"]);
expect(out[4]).toHaveLength(31);
expect(out[5]).toBe("x".repeat(30)); // a surrogate pair is never split
expect(out[5]).toBe(`${"x".repeat(30)}πŸ˜€`); // 31 code points: already valid
for (const name of out) expect(validateSheetName(name)).toBeNull();
});

it("counts code points, as Excel does: 30 x's and an emoji fit, 31 x's and an emoji don't", () => {
expect(validateSheetName(`${"x".repeat(30)}πŸ˜€`)).toBeNull(); // 31 code points, 32 UTF-16 units
expect(validateSheetName(`${"x".repeat(31)}πŸ˜€`)).toBe("too-long");
expect(validateSheetName("πŸ˜€".repeat(31))).toBeNull();
expect(validateSheetName("πŸ˜€".repeat(32))).toBe("too-long");
});

it("sanitizeSheetName cuts to 31 code points without splitting a surrogate pair", () => {
expect(sanitizeSheetName(`${"x".repeat(31)}πŸ˜€`)).toBe("x".repeat(31));
expect(sanitizeSheetName(`${"x".repeat(30)}πŸ˜€πŸ˜€`)).toBe(`${"x".repeat(30)}πŸ˜€`);
expect(sanitizeSheetName("πŸ˜€".repeat(40))).toBe("πŸ˜€".repeat(31));
expect(sanitizeSheetName(`${"x".repeat(30)}'y`)).toBe("x".repeat(30)); // the cut leaves a trailing apostrophe, which goes
for (const name of ["History", "HISTORY", "history"]) expect(sanitizeSheetName(name)).toBe("Sheet");
});

it("the writer accepts a 31-code-point name with an emoji", async () => {
const name = `${"x".repeat(30)}πŸ˜€`;
const bytes = await toUint8Array({ sheets: [{ name, rows: [["a"]] }] });
expect(bytes.length).toBeGreaterThan(0);
await expect(toUint8Array({ sheets: [{ name: `${name}x`, rows: [] }] })).rejects.toMatchObject({ code: "INVALID_SHEET_NAME" });
});
});
Loading