@rosperitus/excelerate 0.14.0 → 0.16.0

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.
package/README.md CHANGED
@@ -11,7 +11,11 @@ npm install @rosperitus/excelerate
11
11
 
12
12
  TypeScript declarations ship with the package. Only need to read? The
13
13
  `@rosperitus/excelerate-reader` package has the reading half of the API in a
14
- wasm file of 1.0 MB instead of 2.3 MB.
14
+ wasm file of 1.4 MB instead of 3.9 MB (0.6 MB against 1.5 MB gzipped).
15
+
16
+ The examples use `import`: a project needs `"type": "module"` in its
17
+ `package.json` for that (`npm init -y` writes `"commonjs"`), or `require`
18
+ works the same - `const { Book } = require("@rosperitus/excelerate")`.
15
19
 
16
20
  ## Quick start
17
21
 
@@ -63,10 +67,118 @@ writeFileSync("report.xlsx", book.toXlsx());
63
67
  Continue a series the way the fill handle does:
64
68
 
65
69
  ```ts
70
+ import { Book } from "@rosperitus/excelerate";
71
+
72
+ const book = new Book();
66
73
  book.setRange(0, "F1", [["Jan", "Кв1", 1], [null, null, 3]]);
67
74
  book.fillSeries(0, "F1:H6", "down"); // Feb..Jun, Кв2..Кв6, 5, 7, 9, 11
68
75
  ```
69
76
 
77
+ Clean up imported data, then ask what input reaches a target:
78
+
79
+ ```ts
80
+ import { Book } from "@rosperitus/excelerate";
81
+
82
+ const book = new Book();
83
+ book.setRange(0, "A1", [["Ann;41"], ["Bob;37"], ["ann;41"]]);
84
+ book.textToColumns(0, "A1:A3", { delimiters: ";" }); // Ann | 41 ...
85
+ book.removeDuplicates(0, "A1:B3"); // { removed: 1, remaining: 2 }
86
+
87
+ book.setRange(0, "D1", [[0.01, "=PMT(D1,36,-10000)"]]);
88
+ const { value } = book.goalSeek(0, "E1", 300, "D1"); // the monthly rate: 0.0042...
89
+
90
+ book.addDataValidation(0, { sqref: "B1:B100", type: "whole", formula1: "18", formula2: "99" });
91
+ book.checkValidation(0, "B5", 12); // { style: "stop", ... }
92
+ ```
93
+
94
+ ## In the browser
95
+
96
+ The package carries a second build for browsers and bundlers (Vite, webpack,
97
+ esbuild), and the same import picks it there. The one difference from Node:
98
+ the module has to be started first, which fetches the `.wasm`:
99
+
100
+ ```ts
101
+ import init, { Book } from "@rosperitus/excelerate";
102
+
103
+ await init();
104
+ const file = document.querySelector("input[type=file]") as HTMLInputElement;
105
+ const book = Book.read(new Uint8Array(await file.files![0].arrayBuffer()));
106
+ const blob = new Blob([book.toXlsx()]);
107
+ ```
108
+
109
+ The `.wasm` is fetched from beside the module, so the server should send it as
110
+ `application/wasm`; then the browser compiles it as it streams. Without a
111
+ bundler, an import map pointing at `@rosperitus/excelerate/web/index.js` does
112
+ the same. `@rosperitus/excelerate/web` names the browser build explicitly,
113
+ which also runs in Node given the bytes: `await init({ module_or_path: bytes })`.
114
+
115
+ ## Objects and chains
116
+
117
+ `Book` is one flat class addressed by sheet index. Over it sit `Workbook`,
118
+ `Sheet`, `Table` and `SheetRange`: a workbook hands out sheets, a sheet hands
119
+ out tables and ranges, and every call that changes something returns its
120
+ object, so calls chain.
121
+
122
+ ```ts
123
+ import { Workbook } from "@rosperitus/excelerate";
124
+ import { writeFileSync } from "node:fs";
125
+
126
+ const wb = new Workbook();
127
+ const sales = wb
128
+ .addSheet("Sales") // a new workbook's first sheet, renamed
129
+ .addTableFromData("Sales", "A1", [
130
+ ["Region", "Manager", "Amount"],
131
+ ["North", "Ivanov", 120],
132
+ ["South", "Petrov", 340],
133
+ ["West", "Kozlov", 210],
134
+ ["South", "Smirnov", 95],
135
+ ])
136
+ .set(1, "Amount", 125) // data row 1, by header
137
+ .addFilter("Region", { values: ["South", "West"] })
138
+ .addFilter("Amount", { custom: [{ op: ">", value: 100 }] });
139
+
140
+ sales.records({ visible: true }); // [{ Region: "South", Manager: "Petrov", Amount: 340 }, ...]
141
+ sales.range().visibleValues(); // the same with the header, as a grid
142
+ sales.sheet.style("A1:C1", { font: { bold: true } }).width("B", 14);
143
+ writeFileSync("sales.xlsx", wb.toXlsx());
144
+ ```
145
+
146
+ A filter is Excel's own: the criteria go into the table's `<autoFilter>`, and
147
+ the rows they reject are hidden in the file, so Excel opens it already
148
+ filtered. Criteria on several columns all have to hold. `{ values }` keeps
149
+ the rows whose cell shows one of them (`blank: true` adds the empty ones),
150
+ `{ custom }` takes one or two comparisons (`=`, `<>`, `>`, `>=`, `<`, `<=`;
151
+ `*` and `?` in `=` and `<>`; `and: true` to need both), `{ top: n }` and
152
+ `{ bottom: n }` the extremes, `percent: true` for a share. `clearFilter()`
153
+ takes them off.
154
+
155
+ Every `Book` method that takes the sheet first is a `Sheet` method without
156
+ it, and every one that takes no sheet a `Workbook` method: what `Book`
157
+ answers with nothing returns the object, so it chains, and the rest return
158
+ their answer. So the whole flat API is there:
159
+
160
+ ```ts
161
+ const sheet = wb.sheet("Sales")
162
+ .setColumnWidth(2, 14)
163
+ .setRowHidden(5, true)
164
+ .insertRows(8, 2)
165
+ .setCellStyle("A1", { font: { bold: true } });
166
+ sheet.getRange("A1:C3"); // a query answers: CellGrid
167
+ sheet.columnWidth(2); // 14
168
+ wb.setDefinedName("Total", "Sales!$C$9").definedNames();
169
+ ```
170
+
171
+ On top of that a few have their own shape: `write`, `range`, `style`,
172
+ `width`, `freeze`, `addTable`, `addTableFromData`, `table`, `rename`,
173
+ `activate`, `recalculate` and `remove` on a sheet; `sheet`, `addSheet` and
174
+ `Workbook.readCsv` on the workbook.
175
+
176
+ The objects are handles - a sheet index, a table name, an address - and work
177
+ through `workbook.book`. A
178
+ sheet removed or moved through the `Book` moves the indexes under them, as it
179
+ does for any index. `Workbook.read(bytes)` opens a file; `Book` and its flat
180
+ API are unchanged.
181
+
70
182
  ## API
71
183
 
72
184
  ```ts
@@ -146,6 +258,11 @@ class Book {
146
258
  removeRows(sheet: number, at: number, count: number): void;
147
259
  insertColumns(sheet: number, at: number, count: number, copyOrigin?: CopyOrigin): void; // 1-based
148
260
  removeColumns(sheet: number, at: number, count: number): void;
261
+ // Many places in one pass: [at, count] pairs, numbered as before the call
262
+ insertRowsMany(sheet: number, places: [number, number][], copyOrigin?: CopyOrigin): void;
263
+ removeRowsMany(sheet: number, places: [number, number][]): void;
264
+ insertColumnsMany(sheet: number, places: [number, number][], copyOrigin?: CopyOrigin): void;
265
+ removeColumnsMany(sheet: number, places: [number, number][]): void;
149
266
  copyRange(sheet: number, range: string, to: string, toSheet?: number): void; // formulas rewritten
150
267
  moveRange(sheet: number, range: string, to: string, toSheet?: number): void; // formulas kept, references follow
151
268
  insertCells(sheet: number, range: string, shift: "down" | "right", copyOrigin?: CopyOrigin): void;
@@ -159,14 +276,24 @@ class Book {
159
276
  fillRight(sheet: number, range: string): void;
160
277
  fillSeries(sheet: number, range: string, direction: "down" | "right" | "up" | "left"): void;
161
278
 
279
+ // Data tools, as Excel's Remove Duplicates, Text to Columns and Data Validation
280
+ removeDuplicates(sheet: number, range: string, options?: RemoveDuplicatesOptions): DuplicatesRemoved;
281
+ textToColumns(sheet: number, range: string, options: TextToColumnsOptions): number;
282
+ addDataValidation(sheet: number, rule: NewDataValidation): void;
283
+ checkValidation(sheet: number, address: string, value: CellValue): ValidationProblem | null;
284
+ invalidCells(sheet: number): string[]; // Circle Invalid Data
285
+ validationList(sheet: number, address: string): string[]; // a drop-down's choices
286
+
162
287
  // What is on a sheet besides cells
163
288
  comments(sheet: number): SheetComment[];
164
289
  hyperlinks(sheet: number): SheetHyperlink[];
165
290
  tables(sheet: number): SheetTable[];
166
- charts(sheet: number): SheetChart[];
291
+ charts(sheet: number): SheetChart[]; // with the chart and plot area fill and outline
167
292
  images(sheet: number): SheetImage[]; // without the bytes
168
293
  imageData(sheet: number, index: number): Uint8Array;
169
- shapes(sheet: number): SheetShape[];
294
+ shapes(sheet: number): SheetShape[]; // rotation, flips, fill, line, font as Excel shows them
295
+ setShapeFormat(sheet: number, index: number, patch: ShapeFormatPatch): void; // fill, line, font, rotation, flips
296
+ setChartFormat(sheet: number, index: number, patch: ChartFormatPatch): void; // chart and plot area fill and outline
170
297
 
171
298
  // Style: read whole, written as a patch over what the cell has
172
299
  cellStyle(sheet: number, address: string): CellStyle; // numberFormat, font, fill, borders, alignment
@@ -175,7 +302,9 @@ class Book {
175
302
  setCellStyleAt(sheet: number, row: number, column: number, patch: CellStylePatch): void;
176
303
  setRangeStyle(sheet: number, range: string, patch: CellStylePatch): void;
177
304
  getRichText(sheet: number, address: string): TextRun[] | null; // [{ text, font }]
305
+ getRichTextAt(sheet: number, row: number, column: number): TextRun[] | null;
178
306
  setRichText(sheet: number, address: string, runs: TextRun[]): void;
307
+ setRichTextAt(sheet: number, row: number, column: number, runs: TextRun[]): void;
179
308
 
180
309
  // Notes, links, tables
181
310
  setComment(sheet: number, address: string, author: string, text: string): void;
@@ -184,6 +313,7 @@ class Book {
184
313
  removeHyperlink(sheet: number, range: string): boolean;
185
314
  addTable(sheet: number, name: string, range: string, headerRow?: boolean): void;
186
315
  removeTable(sheet: number, name: string): boolean;
316
+ setTableFilter(name: string, column: string | number, criteria: TableFilter | null): void; // hides the rows that fail
187
317
 
188
318
  // The saved view
189
319
  sheetView(sheet: number): SheetViewInfo;
@@ -196,6 +326,10 @@ class Book {
196
326
  setDefinedName(name: string, formula: string, sheet?: number): void;
197
327
  removeDefinedName(name: string, sheet?: number): boolean;
198
328
 
329
+ // File > Info: title, author, company, and fields of your own
330
+ documentProperties(): DocumentProperties;
331
+ setDocumentProperties(patch: DocumentPropertiesPatch): void; // null clears a field
332
+
199
333
  // Rules a file states
200
334
  dataValidations(sheet: number): SheetValidation[];
201
335
  conditionalFormats(sheet: number): SheetConditionalFormat[];
@@ -219,6 +353,7 @@ class Book {
219
353
  recalculateCell(sheet: number, address: string): boolean;
220
354
  recalculateFrom(sheet: number, address: string): number;
221
355
  recalculateFromMany(sheet: number, addresses: string[]): number;
356
+ goalSeek(sheet: number, set: string, target: number, changing: string, options?: GoalSeekOptions): GoalSeekResult;
222
357
 
223
358
  // Functions of your own, for names no built-in claims
224
359
  registerFunction(name: string, fn: (...args: (CellValue | CellGrid)[]) => CellValue | CellGrid): void;
@@ -261,6 +396,14 @@ missing sheet, a truncated package.
261
396
  workbook, not one sheet: `$A$5` becomes `$A$6`, a range that lost cells
262
397
  narrows, a deleted cell reads `#REF!`, and drawings and tables follow. The
263
398
  cached result of a rewritten formula is dropped, so recalculate after.
399
+ An insert that would push a filled cell or a merge off the last row or
400
+ column throws and leaves the book as it was, as Excel refuses it.
401
+ - **Many rows at once.** Every edit walks the whole workbook, so a loop of
402
+ `insertRows` costs a walk per row. `insertRowsMany(0, [[5, 1], [9, 1],
403
+ [14, 1]])` does it in one: places are numbered as the sheet was before the
404
+ call, in any order. Subtotal rows under 4 000 groups of 40 000 rows took
405
+ 73 s one at a time and take 29 ms this way. `removeRowsMany` and the column
406
+ pair work the same.
264
407
  - **Style is a patch.** `setCellStyle(0, "A1", { font: { bold: true } })` keeps
265
408
  the number format the cell had. Equal styles share one entry in the
266
409
  workbook's table, so painting a column costs one style, not one per cell -
@@ -280,9 +423,18 @@ missing sheet, a truncated package.
280
423
  - **Read and write formatting by the block.** `getRangeStyles` returns each
281
424
  distinct style once and a grid of indexes into them; `setRangeStyles` takes
282
425
  the same shape back, so copying a block's look is two calls.
283
- - **Charts, pictures and shapes are read-only here.** `charts`, `images` and
284
- `shapes` describe what a sheet carries; the parts themselves travel through
285
- a write byte for byte.
426
+ - **Charts, pictures and shapes travel byte for byte; their look is a patch.**
427
+ `charts`, `images` and `shapes` describe what a sheet carries, and an
428
+ untouched object goes back into the file as it came. A shape's `fill`,
429
+ `line` and `font` are what Excel shows, its style filling in what the shape
430
+ leaves out, and a colour comes resolved through the theme:
431
+ `{ type: "solid", color: "#FF4472C4" }`. `setShapeFormat(0, 2, { fill: {
432
+ type: "solid", color: "accent2" }, line: { width: 2 }, rotation: 15 })`
433
+ changes only what it names - `null` gives a fill or line back to the style -
434
+ and only those elements are rewritten; effects, other runs and dashes stay.
435
+ A colour to write is `#RRGGBB`, `#AARRGGBB` or a theme name (`accent1`,
436
+ `tx1`, `bg2`) that follows the theme. `setChartFormat` does the same for a
437
+ chart's chart area (`format`) and plot area (`plotFormat`).
286
438
  - **Functions of your own.** `book.registerFunction("MYTOTAL", (range) =>
287
439
  range.flat().reduce((a, b) => a + (b ?? 0), 0))` - arguments arrive
288
440
  evaluated, a range as a grid. A built-in name stays the built-in's, an
@@ -318,19 +470,19 @@ This folder is both the published package's readme and the workspace that
318
470
  builds and exercises it.
319
471
 
320
472
  ```
321
- ../tools/build-npm.sh # wasm-pack --release --target nodejs -> npm/pkg
473
+ ../build-npm.sh # wasm-pack --release --target nodejs -> npm/pkg
322
474
  npm install && npm test # tests against the freshly built package
323
475
  npm start # example.js: build a book, calculate, round-trip
324
476
  npm run ts # typescript/basic.ts, no build step
325
477
  npm run typecheck # tsc --strict over the TypeScript examples
326
478
  npm run bench [iterations] # parse timings, median and best
327
- ../tools/pack-npm.sh # pkg -> pkg-publish, then: cd pkg-publish && npm publish --otp=...
479
+ ../pack-npm.sh # pkg -> pkg-publish, then: cd pkg-publish && npm publish --otp=...
328
480
  ```
329
481
 
330
482
  | Path | What it is |
331
483
  |---|---|
332
484
  | `pkg/` | build output for Node (git-ignored); `pkg-web/` and `pkg-bundler/` for the other targets |
333
- | `pkg-publish/` | `tools/pack-npm.sh`: a copy of `pkg/` renamed to `@rosperitus/excelerate`, the folder `npm publish` runs in (git-ignored) |
485
+ | `pkg-publish/` | `pack-npm.sh`: a copy of `pkg/` renamed to `@rosperitus/excelerate`, the folder `npm publish` runs in (git-ignored) |
334
486
  | `example.js`, `test.js`, `bench.js` | JavaScript examples, tests, benchmark |
335
487
  | `typescript/` | TypeScript examples, run from here: `node typescript/basic.ts` (Node 22.6+). No node_modules of their own - they resolve the package from this folder |
336
488
  | `browser/` | the same API in a page: `index.html` over `pkg-web/` |