Skip to content

feat(worksheet): insert and delete whole rows - #318

Merged
baseballyama merged 3 commits into
mainfrom
feat/issue-313-insert-delete-rows
Nov 9, 2026
Merged

baseballyama merged 3 commits into
mainfrom
feat/issue-313-insert-delete-rows

Conversation

@baseballyama

Copy link
Copy Markdown
Member

Summary

Adds insertRows(wb, ws, at, count?) and deleteRows(wb, ws, at, count?) to @office-kit/xlsx/worksheet. They behave like Excel's Insert/Delete ▸ Sheet Rows: everything with a row position moves, and every formula in the workbook that points at the sheet is rewritten.

Motivation

Filling templates whose sections grow or shrink at export time needs whole-row edits that keep SUM ranges, merges, row heights, print areas and defined names in step. Nothing in the public API does this today; copyRange / moveRange move cells only. Spec agreed in #313 (comment).

Closes #313

Changes

  • New insertRows / deleteRows (src/worksheet/structure.ts).
  • Moves cells, row dimensions, merges, hyperlinks, notes (and their box), threaded comments, data validations, conditional formats, tables (+ filter / sort), AutoFilter, sort state, protected ranges, ignored errors, cell watches, smart tags, scenarios, selections, row breaks, custom views, web-publish items, sparklines, drawing anchors (including verbatim anchors), x14 xm:sqref, modelled pivot tables and consolidation sources.
  • Rewrites formulas in cells on every sheet, defined names, CF / DV rules, table column formulas, sparklines, charts (legacy and chartex, chartsheets included) and x14 xm:f. References move with their cells ($ ones too), straddling ranges grow or shrink, deleted references become #REF!; whole-column, 3-D and external references are left alone. The rewrite splices the original text, so spacing and casing survive (src/formula/structure.ts).
  • A CF / DV formula whose anchor row is deleted is re-based on the new top-left cell first, as Excel does.
  • Shared-formula groups the edit reaches are written back as plain formulas.
  • Inserted rows take the row above's height and cell styles; merges are not duplicated.
  • All-or-nothing: unsupported edits throw OpenXmlSchemaError before any change, and formula rewrites are computed before the first mutation. Rejected: cutting through an array formula / data table / pivot report, deleting a table's header or totals row, all its data rows or the whole table, deleting a pivot's whole source, a scenario changing cell or a consolidation source, pushing cells past row 1048576, and sheets with passthrough pivots or OLE objects / form controls.
  • openpyxl migration guide lists the new functions.

Testing

  • tests/formula/structure.test.ts: reference rewriting (anchors, ranges, flipped ranges, row ranges, quoting, 3-D / external / structured / names, #REF!, whitespace preserved).
  • tests/worksheet/structure.test.ts: the issue's CV template (SUM, merges, heights, styles, print area, names), cross-sheet formulas, DV / CF / hyperlinks / notes, tables, charts / anchors / sparklines / pivots, shared and array formulas, re-anchored rule formulas, every rejection leaving the workbook unchanged, save + validateXlsx + reload.
  • One-off run over all 44 .xlsx / .xlsm fixtures in the repo: insert 3 rows at 2 and delete 2 rows at 2 on every sheet, save, validate. No save failures and no validation regressions; the only throws were the documented rejections.
  • Opened the generated files (template with table, DV, CF, note, sparkline, chart, pivot, names; after insert and after delete; plus an Excel-authored fixture after insert) in Excel for Mac: all open without repair, recalculated totals are correct.
  • pnpm prepublishOnly passes (API baseline updated for the two new exports).
pnpm vitest run tests/formula/structure.test.ts tests/worksheet/structure.test.ts

Breaking changes

None

Checklist

  • I have read CLAUDE.md and followed the project's conventions.
  • I have added or updated tests for the change.
  • I have added or updated documentation where user-visible behavior changed.
  • If this is a user-visible change, I have run pnpm changeset and committed
    the result.
  • If this is a breaking change, I have flagged it above and the changeset is
    marked accordingly.
  • I have re-read my own diff and removed dead code, debug prints, and stale
    comments.
  • If I used an LLM to draft this PR, I have verified each change myself, this
    PR represents real work that warrants a maintainer's review, and I am
    willing to defend each line in review.

🤖 Generated with Claude Code

https://claude.ai/code/session_01MNFNHrh8yhz9PQ3bWTPBHo

insertRows / deleteRows move everything that carries a row position and
rewrite every formula in the workbook that points at the edited sheet,
following Excel's rules. Edits that would leave a wrong file are rejected
before the first mutation.

Closes #313

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNFNHrh8yhz9PQ3bWTPBHo
Copilot AI balanced review requested due to automatic review settings November 8, 2026 23:26

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@Riyooo

Riyooo commented Nov 9, 2026

Copy link
Copy Markdown

Thanks for taking this on, and so quickly.

I ran this branch (858268c) on the template I described in #313. The new rows, the SUM ranges, the merges and the names come out right, but Excel asks to repair every file it produces. The cause seems to be a stale xl/calcChain.xml.

As far as I can see, the loader keeps the calc chain as a passthrough part, and the edit doesn't touch it. The chain lists formula cells by address, so once the totals move down it still names their old cells, which no longer hold formulas. Excel then offers to repair the file, with this log:

Removed Records: Formula from /xl/calcChain.xml part (Calculation properties)

Same result after deleteRows, and with fullCalcOnLoad set. A fixture already in the repo seems to have the same shape: reference/openpyxl/openpyxl/tests/data/genuine/sample.xlsx chains only D2 on Sheet3 - Formulas, and inserting a row at 1 moves that formula to D3:

const wb = await loadWorkbook(fromFile('reference/openpyxl/openpyxl/tests/data/genuine/sample.xlsx'));
const ws = getSheet(wb, 'Sheet3 - Formulas');
if (ws) insertRows(wb, ws, 1);
await saveWorkbook(wb, toFile('out.xlsx'));

Since Excel rebuilds a missing chain, one option might be to drop it when rows are inserted or deleted: the part, its content-type override and its workbook relationship. You'll know better what fits the codebase.

A smaller thing I noticed: a rewritten formula keeps its cached value, and Excel shows cached values as they are when it opens a file last saved by a recent Excel. I'd expect a SUM that deleteRows shrinks over a filled row to keep showing the old total until a full recalculation. Clearing the cached value of rewritten formulas and setting fullCalcOnLoad could be one way to handle it; a note in the JSDoc pointing at setFullCalcOnLoad could be another, if you'd rather leave it to the caller.

@baseballyama

Copy link
Copy Markdown
Member Author

@Riyooo Thank you for checking! This is a bit tricky to handle, so I really appreciate you testing it. I'll try to make some further adjustments based on your results.

…s in row edits

- Drop the calc chain and set fullCalcOnLoad, so Excel neither asks to
  repair the file nor shows stale cached results.
- Move pivot tables kept as passthrough parts instead of refusing the edit.
- Keep ranges ending at row 1048576 pinned on deletion.
- Grow ranges covering a table's data body when rows land at its first
  data row or totals row.
- Grow conditional formats and validations ending right above inserted
  rows, and split them where relative references no longer agree, as
  Excel does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@baseballyama

Copy link
Copy Markdown
Member Author

Thanks for testing it on the real template. Fixed in 5300449.

Calc chain: both edits now drop xl/calcChain.xml, along with its content-type override and workbook relationship. Excel rebuilds it on open. Your sample.xlsx repro now opens without the repair prompt.

Cached values: both edits also set fullCalcOnLoad, so Excel recalculates on open. I kept the cached values rather than clearing them. Clearing only the rewritten formulas would miss formulas that read a resized range through a name, and viewers that don't calculate would show blanks. The JSDoc now says this and points at setFullCalcOnLoad.

I also ran about 120 insert/delete cases through real Excel and compared its output with ours. That found a few more mismatches, now fixed: ranges ending at row 1048576 stay pinned on delete, ranges covering a table body grow when rows are inserted at its first data row or totals row, conditional formats and validations ending right above an insertion grow over it, and they split the way Excel splits them when relative references cross the edit. Pivot tables the model doesn't carry now move with their rows instead of making the edit throw. Every output opened in Excel without a repair prompt.

@Riyooo

Riyooo commented Nov 9, 2026

Copy link
Copy Markdown

That fixes it on my side. I re-ran 5300449 on the same template: the files open in Excel without the repair prompt, and the totals come out right after both insertRows and deleteRows. Keeping the cached values makes sense to me. Thanks again!

@baseballyama
baseballyama merged commit 49e1821 into main Nov 9, 2026
16 checks passed
@baseballyama
baseballyama deleted the feat/issue-313-insert-delete-rows branch November 9, 2026 11:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: insert and delete whole rows, moving everything that carries a position

3 participants