iOfficeAI/OfficeCLI · error · ArgumentException

Sheet not found: {sheetName}

Error message

Sheet not found: {sheetName}

What it means

Thrown by ExcelHandler.AddRow when the sheet name extracted from the parent path does not match any worksheet in the workbook. The parent path is split on '/' to extract the sheet name as the first segment, and FindWorksheet returns null when no worksheet has that name. This is the row-insertion equivalent of a missing-sheet error.

Source

Thrown at src/officecli/Handlers/Excel/ExcelHandler.Add.Cells.cs:174

        if (sheet.State != null && sheet.State.Value != SheetStateValues.Visible) return false;
        if (sheet.Id?.Value == null) return false;
        if (workbookPart.GetPartById(sheet.Id.Value) is not WorksheetPart wsp) return false;
        var ws = wsp.Worksheet;
        if (ws == null) return false;
        var sheetData = ws.GetFirstChild<SheetData>();
        if (sheetData != null && sheetData.Elements<Row>().Any()) return false;
        var props = ws.GetFirstChild<SheetProperties>();
        if (props?.GetFirstChild<TabColor>() != null) return false;
        if (ws.Descendants<AutoFilter>().Any()) return false;
        return true;
    }

    private string AddRow(string parentPath, string type, InsertPosition? position, Dictionary<string, string> properties)
    {
        var segments = parentPath.TrimStart('/').Split('/', 2);
        var sheetName = segments[0];
        var worksheet = FindWorksheet(sheetName)
            ?? throw new ArgumentException($"Sheet not found: {sheetName}");
        var sheetData = GetSheet(worksheet).GetFirstChild<SheetData>()
            ?? GetSheet(worksheet).AppendChild(new SheetData());

        // Resolve --before / --after anchors (same shape as Excel CopyFrom):
        // anchor must be /<sheetName>/row[K] in the same sheet.
        // CONSISTENCY(zero-based-index): per project convention, position.Index
        // is 0-based across all formats (--index 0 = head, --index 1 = before
        // 2nd slot). xlsx Row uses a 1-based RowIndex internally, so +1 here
        // and let the existing branch keep treating `index` as a 1-based row
        // number (which is also what the anchor branch below produces).
        int? index = position?.Index.HasValue == true ? position!.Index!.Value + 1 : (int?)null;
        if (index == null && position != null && (position.After != null || position.Before != null))
        {
            int FindAnchorRow(string anchorPath)
            {
                var aSegs = anchorPath.TrimStart('/').Split('/', 2);
                if (aSegs.Length < 2)
                    throw new ArgumentException(

View on GitHub (pinned to 1ced45e900)

Solutions

  1. Verify the sheet name exists: list sheets with a query on '/' first.
  2. Check the path structure: it should be '/<sheetName>' for adding rows.
  3. Ensure any preceding 'add sheet' command in the batch succeeded.
  4. If the sheet name is computed, add a null/empty check before constructing the path.
Defensive patterns

Strategy: validation

Validate before calling

// Verify the sheet exists before adding rows
if (handler.FindWorksheet(sheetName) == null)
    throw new InvalidOperationException($"Sheet '{sheetName}' does not exist.");
handler.Add($"/{sheetName}", "row", position, properties);

Try / catch

try
{
    handler.Add($"/{sheetName}", "row", position, properties);
}
catch (ArgumentException ex) when (ex.Message.StartsWith("Sheet not found"))
{
    // Sheet does not exist — create it first or report the error
    logger.LogError("Sheet '{Sheet}' not found. Create it first.", sheetName);
    throw;
}

Prevention

When it happens

Trigger: Calling Add with a path like '/NonexistentSheet/row' where 'NonexistentSheet' does not exist. The parent path is expected to be '/<sheetName>' for row insertion. Also triggered if the sheet name has a typo or casing mismatch (FindWorksheet resolution behavior).

Common situations: A batch replay where an 'add sheet' command was supposed to create the sheet first but failed; a typo in the sheet name; a path constructed dynamically where the sheet-name variable was empty or wrong; referencing a sheet that was deleted in a concurrent modification.

Related errors


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