iOfficeAI/OfficeCLI · error · ArgumentException

Invalid sheet name '{name}': cannot start or end with an apo

Error message

Invalid sheet name '{name}': cannot start or end with an apostrophe (').

What it means

Excel rejects sheet names that start or end with an apostrophe because the single quote is the escape character used to quote sheet names containing spaces or symbols in formulas (e.g. 'My Data'!A1). A leading/trailing quote would make such references ambiguous.

Source

Thrown at src/officecli/Handlers/Excel/ExcelHandler.Helpers.Validation.cs:332

                    "Excel limits: rows 1-1048576, columns A-XFD.");
            }
        }
    }

    internal static void ValidateSheetName(string name)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("Invalid sheet name: name cannot be empty or whitespace.");
        if (name.Length > 31)
            throw new ArgumentException(
                $"Invalid sheet name '{name}': length {name.Length} exceeds Excel's 31-char limit.");
        var forbidden = new[] { '\\', '/', '?', '*', ':', '[', ']' };
        var hit = name.IndexOfAny(forbidden);
        if (hit >= 0)
            throw new ArgumentException(
                $"Invalid sheet name '{name}': contains forbidden character '{name[hit]}'. Excel rejects any of: \\ / ? * : [ ]");
        if (name.StartsWith('\'') || name.EndsWith('\''))
            throw new ArgumentException(
                $"Invalid sheet name '{name}': cannot start or end with an apostrophe (').");
        if (name.Equals("History", StringComparison.OrdinalIgnoreCase))
            throw new ArgumentException(
                "Invalid sheet name 'History': reserved by Excel for the change-history sheet.");
    }

    /// <summary>
    /// R35-3: cross-workbook cell formulas like "=[Other.xlsx]Sheet1!A1" or
    /// "=[1]Sheet1!A1" need an externalLinks part to resolve. Without one,
    /// Excel opens the file but the formula shows #REF!. Reject up-front
    /// rather than silently persist a broken formula.
    /// CONSISTENCY(cross-workbook-ref): mirrors the namedrange refersTo
    /// guard in ExcelHandler.Add.Tables.cs (R27-1).
    /// </summary>
    internal static void RejectCrossWorkbookFormula(string formula)
    {
        if (string.IsNullOrEmpty(formula)) return;
        var trimmed = formula.TrimStart('=', ' ', '\t');

View on GitHub (pinned to 1ced45e900)

Solutions

  1. Trim leading and trailing apostrophes from the name.
  2. Validate at the input boundary and strip stray quotes.
  3. If the quote is meaningful, embed it inside the name rather than at an edge.

Example fix

// before
wb.AddSheet("'Q1 Data'");

// after
var name = userSheetName.Trim(' \'');
wb.AddSheet(name);
Defensive patterns

Strategy: validation

Validate before calling

static string TrimApostropheEdges(string n) =>
    (n.StartsWith('\'') || n.EndsWith('\'')) ? n.Trim('\'') : n;

Try / catch

try { wb.AddSheet(name); }
catch (ArgumentException ex) when (ex.Message.Contains("apostrophe")) {
    wb.AddSheet(name.Trim('\''));
}

Prevention

When it happens

Trigger: A sheet name whose first or last character is the apostrophe ('). The StartsWith('') / EndsWith('') check trips after the forbidden-char check.

Common situations: Copy-paste artifacts that drag in a trailing quote; typographic apostrophes converted to straight quotes; data labels that begin or end with a possessive.

Related errors


AI-assisted analysis of iOfficeAI/OfficeCLI@1ced45e900 (2026-08-13). Data as JSON: /api/errors/179f6039430264f7. Report an issue: GitHub.