iOfficeAI/OfficeCLI · error · ArgumentException

Target sheet not found: {tgtSegments[0]}

Error message

Target sheet not found: {tgtSegments[0]}

What it means

Thrown for a row move when targetParentPath (--to) is non-empty but its first segment does not name an existing worksheet (FindWorksheet on tgtSegments[0] returned null). The handler resolves the destination SheetData by sheet name, so an unknown target sheet aborts before any row is detached.

Source

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

        var elementRef = segments[1];
        var sheetData = GetSheet(worksheet).GetFirstChild<SheetData>()
            ?? throw new ArgumentException("Sheet has no data");

        // Determine the target sheet's SheetData. The result path is built from
        // the resolved target SHEET (below), NOT the raw --to: a row/col/cell
        // lives directly under a sheet, so a non-sheet --to like /Sheet1/row[2]
        // must not leak into the result path (it used to produce a doubled
        // /Sheet1/row[2]/row[3]). Only the sheet segment of --to is meaningful.
        SheetData targetSheetData;
        if (string.IsNullOrEmpty(targetParentPath))
        {
            targetSheetData = sheetData;
        }
        else
        {
            var tgtSegments = targetParentPath.TrimStart('/').Split('/', 2);
            var tgtWorksheet = FindWorksheet(tgtSegments[0])
                ?? throw new ArgumentException($"Target sheet not found: {tgtSegments[0]}");
            targetSheetData = GetSheet(tgtWorksheet).GetFirstChild<SheetData>()
                ?? throw new ArgumentException("Target sheet has no data");
        }

        // Find and move the row
        var rowMatch = Regex.Match(elementRef, @"^row\[(\d+)\]$");
        if (rowMatch.Success)
        {
            var rowIdx = int.Parse(rowMatch.Groups[1].Value);
            // Try ordinal lookup first (Nth row element), then fall back to RowIndex
            var allRows = sheetData.Elements<Row>().ToList();
            var row = (rowIdx >= 1 && rowIdx <= allRows.Count ? allRows[PathIndex.ToArrayIndex(rowIdx)] : null)
                ?? sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex?.Value == (uint)rowIdx)
                ?? throw new ArgumentException($"Row {rowIdx} not found");

            // Resolve --before / --after anchors to a 0-based document-order
            // position in the target sheet. Anchor must be /<TargetSheet>/row[K].
            // Resolved BEFORE removing the moved row so the anchor is found by

View on GitHub (pinned to 1ced45e900)

Solutions

  1. Confirm the target sheet exists (handler.Get("/", depth:1)) before the cross-sheet move.
  2. Create the target sheet first via Add if it should exist.
  3. Pass null/empty targetParentPath to move within the same sheet.

Example fix

// before
h.Move("/Sheet1/row[2]", "/Dest", InsertPosition.AtIndex(0)); // 'Dest' missing
// after
h.Add("/", "sheet", null, new(){{"name","Dest"}});
h.Move("/Sheet1/row[2]", "/Dest", InsertPosition.AtIndex(0));
Defensive patterns

Strategy: validation

Validate before calling

if (!string.IsNullOrEmpty(targetParentPath))
{
    var tgt = targetParentPath.TrimStart('/').Split('/', 2)[0];
    var sheets = handler.Get("/", depth: 1).Children.Select(c => c.Name).ToList();
    if (!sheets.Any(s => s.Equals(tgt, StringComparison.OrdinalIgnoreCase)))
        throw new InvalidOperationException($"Target sheet '{tgt}' does not exist");
}

Try / catch

try { handler.Move(src, target, pos); }
catch (ArgumentException ex) when (ex.Message.StartsWith("Target sheet not found"))
{ /* create or choose a valid target sheet, then retry */ }

Prevention

When it happens

Trigger: Move("/Sheet1/row[2]", "/Nope", position) where 'Nope' is not a sheet; target sheet renamed/deleted; --to path malformed so the first segment is wrong.

Common situations: Cross-sheet move to a sheet that was removed; typo in --to; copy-paste of an old path; assuming a sheet exists because it appears in a cached view.

Related errors


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