@sheetxl/skills 0.0.0-stage → 0.8.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,368 @@
1
+ ---
2
+ name: writing
3
+ description: "SheetXL sheet interaction: reading and writing cell values, navigating ranges, applying styles, working with the formula engine — and verifying the change. Load when changing or reading a sheet: setting values, writing formulas, the cursor pattern, styling ranges. Triggers on: ICellRange, ICell, getRange, getRangeAt, getValue, setValue, getText, getCell, setValues, setComputedValues, getStyle, setNumberFormat, number format, getColumnAt, getRowAfter, getCalculation, ready, doBatch, fill a formula across, cursor pattern, navigation."
4
+ ---
5
+
6
+ # Writing — Sheet Interaction
7
+
8
+ > Part of the SheetXL skill suite. See the root `SKILL.md` for routing. Code below
9
+ > is run-context code (`scripting.md`): snippet form — no `await`, and nothing to
10
+ > import (the context is already in scope); every statement auto-awaits. Files
11
+ > open via the workbook argument and save via `--save` (CLI) or sessions
12
+ > (MCP); application code goes through `embedding.md`. To understand structure
13
+ > first, see `reading.md`.
14
+
15
+ **In this file:** Coordinates: two notations · Values: two entry modes (write
16
+ and read via `ICellRange`) · Formulas and the calculation engine · Navigation
17
+ (suffix convention, methods, idioms) · The cursor pattern · Styling · Protected
18
+ sheets · After writing: verify
19
+
20
+ This reference covers interacting with a sheet — reading and writing cell
21
+ values, navigating ranges, and applying styles. In an attended session,
22
+ changes appear in the user's UI immediately — follow the rules in
23
+ `interactive.md`.
24
+
25
+ ---
26
+
27
+ ## Coordinates: Two Notations
28
+
29
+ All index parameters are 0-based. A1 = row 0, column 0. Both notations address the
30
+ same cells — use whichever makes the intent clearest.
31
+
32
+ ```typescript
33
+ // A1 string notation — natural for known addresses and formula strings
34
+ sheet.getRange('B2:D10');
35
+ sheet.getRange('D1').setValue('=SUM(A1:C1)');
36
+
37
+ // 0-based index notation — natural for programmatic and loop-driven navigation
38
+ sheet.getRangeAt(1, 1); // B2 (row, col)
39
+ sheet.getRangeAt(1, 1, 9, 3); // B2:D10 (rowStart, colStart, rowEnd, colEnd)
40
+ ```
41
+
42
+ ---
43
+
44
+ ## Values: Two Entry Modes
45
+
46
+ These are not interchangeable — the display mode goes through the SheetXL text
47
+ parser, which matches Excel input conventions: a literal (`42%`, `1/31/2026`)
48
+ gives a General cell its matching number format, and a cell that already has one
49
+ keeps it. A formula keeps the cell's format either way.
50
+ `setValue('42%')` and `setValue(0.42)` produce different results: the first stores
51
+ `0.42` with a percent format applied; the second stores `0.42` with no format.
52
+
53
+ The full encoding contract — `'` text prefix, formulas, errors, round-trip — is
54
+ the **Value encoding** section of the root `SKILL.md`. It is the same rule in
55
+ both directions and is not repeated here.
56
+
57
+ ### Writing — ICellRange is the write surface
58
+
59
+ ```typescript
60
+ const range = sheet.getRange('A1'); // ICellRange
61
+
62
+ range.setValue('42%'); // display mode — parser applies
63
+ range.setValue(0.42); // typed mode — bypasses parser
64
+ range.setValue('=SUM(A1:C1)'); // '=' prefix triggers formula engine
65
+ range.setValue("'123"); // leading apostrophe forces text storage
66
+ range.setValues([[1, 2], [3, 4]]); // 2D array, rows x columns
67
+ ```
68
+
69
+ `setValue` writes to the **entire range**, and a formula written that way is a
70
+ fill, not a copy: it is read as the top-left cell's formula and every other cell
71
+ gets it with relative references shifted and `$` references pinned, exactly as
72
+ typing it and filling across would. A 60-month row is one call —
73
+ `sheet.getRange('C5:BJ5').setValue('=B5*(1+$B$2)')` — never a loop that builds
74
+ an A1 string per cell.
75
+
76
+ **Transforming what is already there? Do not read it out and write it back.**
77
+ `setComputedValues(fn)` runs the transform inside the engine and the values never
78
+ round-trip through your runtime — it and the whole `IRange` surface are in
79
+ [vector](vector.md). Load it before writing the transform. Reach for
80
+ `getValues()` + a loop + `setValues()` only when you genuinely need JavaScript
81
+ values in hand, which for a transform you do not: the loop moves the work out of
82
+ the engine and copies the grid to do it.
83
+
84
+ ### Reading — ICellRange is the read surface, ICell for per-cell detail
85
+
86
+ `ICellRange` reads with `getValue()` (the top-left scalar) and `getValues()`; to *see*
87
+ a range, return it and its report renders. **`getText()` is on `ICell`, not on the
88
+ range** — `getCell()` gives per-cell detail when you need it (display text, type,
89
+ formula text, interop type) and defaults to the top-left cell:
90
+
91
+ ```typescript
92
+ const range = sheet.getRange('A1'); // ICellRange — write, navigate, read
93
+ const cell = range.getCell(); // ICell — per-cell detail
94
+ ```
95
+
96
+ `ICell` only reads: there is no `setValue` or `setStyle` on it. Write through the range.
97
+
98
+ `range.getFormulas()` reads a whole range's formula text (`'=SUM(A1:C1)'`, `''` where a cell has no formula), and `setFormulas()` writes it back.
99
+
100
+ `getValue()`, `getText()`, and `getType()` are three lenses on the same stored value.
101
+ `getType()` reflects what the engine actually stored — not what you wrote or what it
102
+ looks like:
103
+
104
+ ```typescript
105
+ // Percentage — format inferred from input
106
+ range.setValue('42%');
107
+ cell.getValue() // => 0.42
108
+ cell.getText() // => '42%'
109
+ cell.getType() // => ScalarType.Number
110
+
111
+ // Date — stored as Excel serial number, formatted back through the cell's format
112
+ range.setValue('2024-01-01');
113
+ cell.getValue() // => 45292 (Excel date serial)
114
+ cell.getText() // => '1/1/2024' (the inferred format, not the input spelling)
115
+ cell.getType() // => ScalarType.Number — dates are numbers
116
+
117
+ // Formula — type reflects the computed result, not the expression
118
+ range.setValue('=SUM(A1:C1)');
119
+ cell.getValue() // => 60
120
+ cell.getText() // => '60'
121
+ cell.getType() // => ScalarType.Number
122
+ cell.getFormulaText() // => '=SUM(A1:C1)' (null for non-formula cells)
123
+
124
+ // Force text — leading apostrophe, same convention as Excel
125
+ range.setValue("'123");
126
+ cell.getValue() // => '123'
127
+ cell.getText() // => "'123" (apostrophe restored for round-trip safety)
128
+ cell.getType() // => ScalarType.String
129
+
130
+ // Error — error values are a first-class value type
131
+ range.setValue('#DIV/0!'); // or '=1/0'
132
+ cell.getValue() // => FormulaError.Div0
133
+ cell.getText() // => '#DIV/0!'
134
+ cell.getType() // => ScalarType.Error
135
+ ```
136
+
137
+ `getText()` round-trips through `setValue()` — a value read with `getText()` can
138
+ always be written back and interpreted identically. That is the round trip, not
139
+ the input spelling: `'2024-01-01'` comes back as `'1/1/2024'`, and both name the
140
+ same serial.
141
+
142
+ ---
143
+
144
+ ## Formulas and the Calculation Engine
145
+
146
+ `ready()` is only needed when you write a formula and read its result in the same
147
+ run. Not needed for read-only or write-only workflows.
148
+
149
+ ```typescript
150
+ sheet.getRange('D1').setValue('=SUM(A1:C1)');
151
+ wb.getCalculation().ready();
152
+ sheet.getRange('D1').getValue()
153
+ ```
154
+
155
+ `ready()` returns a promise. A snippet awaits it for you, like every top-level
156
+ statement; a script (default export, `scripting.md`) must `await` it, or the read
157
+ that follows sees the value from before the recalculation. That is the whole
158
+ what-if loop — set an input, wait, read the output:
159
+
160
+ ```typescript
161
+ export default async function main({ wb }: SheetXL.IScript.ScriptContext): Promise<number[]> {
162
+ const sheet = wb.getWorksheet(), results: number[] = [];
163
+ for (const rate of [0.03, 0.04, 0.05]) {
164
+ sheet.getRange('B2').setValue(rate);
165
+ await wb.getCalculation().ready();
166
+ results.push(sheet.getRange('B20').getValue() as number);
167
+ }
168
+ return results;
169
+ }
170
+ ```
171
+
172
+ Wrap related writes in `doBatch` — on the range — to make them one operation
173
+ (one recalculation, one undo step):
174
+
175
+ ```typescript
176
+ sheet.getRange('A1:D1').doBatch(() => {
177
+ sheet.getRange('A1:C1').setValues([[10, 20, 30]]);
178
+ sheet.getRange('D1').setValue('=SUM(A1:C1)');
179
+ });
180
+ wb.getCalculation().ready();
181
+ ```
182
+
183
+ (On MCP, every `run` is already a single commit — `doBatch` matters there for
184
+ grouping recalculation, not undo.)
185
+
186
+ ### Defining a name
187
+
188
+ `addFormula(name, expression, replaceExisting?)` — positional, not an options
189
+ bag. Reached through a sheet it is scoped to that sheet; through the workbook
190
+ it is global. Redefine an existing one with `setExpression`, or pass
191
+ `replaceExisting`; without it a collision throws rather than silently dropping
192
+ the new expression.
193
+
194
+ ```typescript
195
+ wb.getNames().addFormula('TaxRate', '=0.21'); // global
196
+ sheet.getNames().addFormula('Rate', '=0.19'); // scoped to that sheet
197
+ wb.getNames().getByName('TaxRate').setExpression('=0.22'); // redefine, dependents keep resolving
198
+ ```
199
+
200
+ Scope is half a name's identity, so there is no `setScope` — to move one,
201
+ delete it and define it again. Reading a name (`getValue`, `getRanges`,
202
+ `evaluate`) is in `reading.md`.
203
+
204
+ ---
205
+
206
+ ## Navigation
207
+
208
+ `ICellRange` is a live reference to sheet cells — not a snapshot. Navigation methods
209
+ return a new `ICellRange`; the original is unchanged.
210
+
211
+ ### Suffix convention
212
+
213
+ | Suffix | Mode | Behavior |
214
+ |---|---|---|
215
+ | `At(n)` | Absolute 0-based | Goes to that exact row/column regardless of current position |
216
+ | `By(n)` | Relative delta from start | Moves n steps from `rowStart`/`colStart` |
217
+ | `After` | One past the end | Row/column immediately after `rowEnd`/`colEnd` |
218
+ | `Before` | One before the start | Row/column immediately before `rowStart`/`colStart` |
219
+ | `To(end)` | Absolute end position | Moves the bottom-right corner to an absolute coordinate |
220
+
221
+ > **`At` is absolute, not relative.** `cursor.getColumnAt(1)` is always column B
222
+ > even if `cursor` is in column E.
223
+
224
+ > **`By` vs `After`:** `getRowBy(0)` is the first row of the range (identity for a
225
+ > 1-row cursor). To advance past the end use `getRowAfter()`, not `getRowBy(height)`.
226
+
227
+ ### Methods
228
+
229
+ ```typescript
230
+ // Row navigation — result is 1 row tall, same column span
231
+ range.getRowAt(5) // row index 5 (0-based, absolute)
232
+ range.getRowBy(2) // 2 rows past rowStart
233
+ range.getRowAfter() // row immediately after rowEnd
234
+ range.getRowBefore() // row immediately before rowStart
235
+
236
+ // Column navigation — result is 1 column wide, same row span
237
+ range.getColumnAt(2) // column C (index 2, absolute)
238
+ range.getColumnBy(1) // 1 column past colStart
239
+ range.getColumnAfter()
240
+ range.getColumnBefore()
241
+
242
+ // Offset — reposition top-left, size unchanged
243
+ range.getOffsetBy(rowDelta, colDelta)
244
+ range.getOffsetTo(rowStart, colStart)
245
+
246
+ // Resize — move bottom-right corner
247
+ range.getResizeBy(rowDelta, colDelta) // additive: A1.getResizeBy(0,2) -> A1:C1
248
+ range.getResizeTo(rowEnd, colEnd) // fixed end regardless of current size
249
+
250
+ // Other
251
+ range.getTopLeft()
252
+ range.getBottomRight()
253
+ range.getRangeAt(rowStart, colStart, rowEnd?, colEnd?)
254
+ range.getAddress() // A1-style string, safe to embed in formula strings
255
+ ```
256
+
257
+ `getEntireRange()` is on the **sheet**, not the range — `sheet.getEntireRange()`
258
+ is the whole grid.
259
+
260
+ ### Common idioms
261
+
262
+ | Task | Form |
263
+ |---|---|
264
+ | Column B on current cursor row | `cursor.getColumnAt(1)` |
265
+ | First free row below data | `(sheet.getUsedRange()?.getRowAfter()) ?? sheet.getEntireRange().getTopLeft()` |
266
+ | Range address in a formula | `` `=SUM(${range.getAddress()})` `` |
267
+
268
+ ---
269
+
270
+ ## The Cursor Pattern
271
+
272
+ A cursor is an `ICellRange` that advances through a sheet by chaining return values.
273
+ Every range operation — `setValue`, `setValues`, navigation — returns the range it
274
+ affected. The cursor pattern makes this the primary idiom: always update `currentRange`
275
+ from the return value, so the cursor always reflects where the last operation landed.
276
+
277
+ `getColumnAt(n)` addresses columns by absolute index, independent of the cursor's
278
+ current column — this is what makes it safe to reach across columns without losing
279
+ your position.
280
+
281
+ ```typescript
282
+ let currentRange = sheet.getRangeAt(0, 0); // start at A1
283
+
284
+ for (const item of data) {
285
+ currentRange = currentRange.getColumnAt(0).setValue(`'${item.label}`); // col A
286
+ currentRange = currentRange.getColumnAt(1).setValue(item.value); // col B
287
+ currentRange = currentRange.getColumnAt(2).setValues(item.matrix); // col C, may be multi-row
288
+
289
+ currentRange = currentRange.getRowAfter(); // next row
290
+ }
291
+ ```
292
+
293
+ The cursor naturally handles variable-height writes: when `setValues` writes a
294
+ multi-row matrix, `currentRange` reflects the full written extent, so `getRowAfter()`
295
+ always skips past all of it.
296
+
297
+ ---
298
+
299
+ ## Styling
300
+
301
+ `getStyle()` applies to the entire range it is called on. Style the full target range
302
+ in one call — do not loop over individual cells.
303
+
304
+ (Reading is the other half of the Excel-ribbon contract: a range's `getStyle()`
305
+ *reads* as the anchor cell's style, so it is not a uniformity check — that is
306
+ `getRegions(<style features>)` returning a single region; see `reading.md`.)
307
+
308
+ ```typescript
309
+ sheet.getRange('A1:E1').getStyle().getFont().setWeight(700);
310
+ sheet.getRange('A1:E1').getStyle().getFill().setColor('#EEEEEE');
311
+ range.getStyle().getBorders().setOutline({ style: 'double', color: 'blue' });
312
+ range.getStyle().getFont().setColor('#FF0000'); // note: setColor not setFill
313
+ range.getStyle().setNumberFormat('0.00%'); // any Excel format code: '#,##0', 'd-mmm-yyyy', …
314
+ ```
315
+
316
+ The number format is on the style, not the range or the cell. Display-mode input
317
+ infers one for a literal in a General cell (`setValue('42%')`); a formula's result is never formatted
318
+ for you, so set it on any formula cell whose result is a date, time or percent,
319
+ and on typed values.
320
+
321
+ ---
322
+
323
+ ## Protected sheets
324
+
325
+ A protected sheet refuses writes, and a cell that will refuse one looks exactly
326
+ like a cell that will take it. The reports say so **only when protection is in
327
+ force** — an unprotected sheet says nothing — and at the altitude you are about to
328
+ write from:
329
+
330
+ | You returned | What it says |
331
+ |---|---|
332
+ | `wb` | `(protected)` on the sheet's heading, and a `protected` line: where a write is still accepted, how many cells, whether a password is set, whether formulas are hidden. A protected *workbook* adds `Protection: structure locked` under the title — sheets cannot be added, deleted, renamed or moved |
333
+ | the sheet | a `Protection` section: the operations still **allowed** (`sort`, `format cells`, `insert rows` … — anything not listed is refused), and the editable regions, each with why it is editable |
334
+ | a range | `Protection: sheet locked — 3 of 12 cells editable (B2:B4)` as its first line |
335
+ | a cell | `Editable: true` / `false` |
336
+
337
+ ```text
338
+ ## Protection (locked · password)
339
+ allowed sort, format cells
340
+ editable 25 cells · 2 regions
341
+ B4:B22 19×1 always unlocked
342
+ D4:F5 2×3 range Inputs · password
343
+ ```
344
+
345
+ - **`always unlocked`** is a cell format and asks for nothing. **`range Name`** is
346
+ an unlocked range (`sheet.getProtectedRanges()`); with `· password` it takes
347
+ writes only after `item.unlock(password)`.
348
+ - The editable regions are the `unlock` partition —
349
+ `sheet.getRegions('unlock')` returns them to loop over.
350
+ - A refused write fails with the sheet's own message, and the run report points
351
+ at the two lookups above. **Write where the sheet is editable** — that is what
352
+ the author left open, and on a form it is the whole task.
353
+ - When the task really does need a locked cell: `sheet.getProtection().pause()`
354
+ suspends enforcement for the session and `resume()` restores it exactly;
355
+ `unlock()` is a document change — the file saves unprotected. Both need the
356
+ password when one is set, and that is the user's to supply.
357
+ - **Hidden formulas** (`formulas hidden`) read as values everywhere — `getFormula()`
358
+ is `null`, and the cell is absent from the `formula` partition. A formula census
359
+ on such a sheet is short by however many are hidden.
360
+
361
+ ---
362
+
363
+ ## After writing: verify
364
+
365
+ Command success is not correctness evidence. Read back the ranges you changed and
366
+ confirm they hold what you intended — values, formulas, and (after
367
+ `getCalculation().ready()`) computed results — before reporting the change done.
368
+ Fixing errors? The recount discipline lives in `analysis.md`.