iOfficeAI/OfficeCLI · error · ArgumentException

Cannot swap elements across different sheets

Error message

Cannot swap elements across different sheets

What it means

Thrown by Swap when the two paths' sheet segments differ (seg1[0] != seg2[0]). Swap only exchanges rows within a single sheet; it does not transport a row across sheets, so a cross-sheet pair is rejected before any worksheet is opened.

Source

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

            foreach (var cell in row.Elements<Cell>())
            {
                if (cell.CellReference?.Value == null) continue;
                var (col, _) = ParseCellReference(cell.CellReference.Value);
                cell.CellReference = $"{col}{newIdx}";
            }
            newIdx++;
        }
    }

    public (string NewPath1, string NewPath2) Swap(string path1, string path2)
    {
        // Parse both paths: /SheetName/row[N]
        var seg1 = path1.TrimStart('/').Split('/', 2);
        var seg2 = path2.TrimStart('/').Split('/', 2);
        if (seg1.Length < 2 || seg2.Length < 2)
            throw new ArgumentException("Swap requires element paths (e.g. /Sheet1/row[1])");
        if (seg1[0] != seg2[0])
            throw new ArgumentException("Cannot swap elements across different sheets");

        var sheetName = seg1[0];
        var worksheet = FindWorksheet(sheetName)
            ?? throw new ArgumentException($"Sheet not found: {sheetName}");
        var sheetData = GetSheet(worksheet).GetFirstChild<SheetData>()
            ?? throw new ArgumentException("Sheet has no data");

        var rowMatch1 = Regex.Match(seg1[1], @"^row\[(\d+)\]$");
        var rowMatch2 = Regex.Match(seg2[1], @"^row\[(\d+)\]$");
        if (!rowMatch1.Success || !rowMatch2.Success)
            throw new ArgumentException("Swap only supports row[N] elements in Excel");

        var allRows = sheetData.Elements<Row>().ToList();
        var idx1 = int.Parse(rowMatch1.Groups[1].Value);
        var idx2 = int.Parse(rowMatch2.Groups[1].Value);
        var row1 = (idx1 >= 1 && idx1 <= allRows.Count ? allRows[idx1 - 1] : null)
            ?? throw new ArgumentException($"Row {idx1} not found");
        var row2 = (idx2 >= 1 && idx2 <= allRows.Count ? allRows[idx2 - 1] : null)

View on GitHub (pinned to 1ced45e900)

Solutions

  1. Ensure both row paths share the same sheet segment.
  2. To relocate a row across sheets, use Move with targetParentPath instead of Swap.
  3. Derive both paths from the same sheetName variable.

Example fix

// before
h.Swap("/Sheet1/row[1]", "/Sheet2/row[3]"); // different sheets
// after
h.Move("/Sheet1/row[1]", "/Sheet2", InsertPosition.AtIndex(3)); // relocate across sheets via Move
Defensive patterns

Strategy: validation

Validate before calling

var s1 = path1.TrimStart('/').Split('/', 2)[0];
var s2 = path2.TrimStart('/').Split('/', 2)[0];
if (!s1.Equals(s2, StringComparison.OrdinalIgnoreCase))
    throw new ArgumentException($"Swap is single-sheet only ('{s1}' vs '{s2}'); use Move to relocate across sheets");

Type guard

static bool SameSheet(string a, string b) =>
    a.TrimStart('/').Split('/', 2)[0]
     .Equals(b.TrimStart('/').Split('/', 2)[0], StringComparison.OrdinalIgnoreCase);

Prevention

When it happens

Trigger: Swap("/Sheet1/row[1]", "/Sheet2/row[1]"); one path from each of two sheets; sheet rename making previously-equal segments differ.

Common situations: User expects Swap to move a row between sheets (it cannot); copy-paste of paths from different sheets; refactoring that changed one sheet but not the other.

Related errors


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