@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/web/index.js ADDED
@@ -0,0 +1,408 @@
1
+ import * as core from "./excelerate.js";
2
+ export * from "./excelerate.js";
3
+ export { default } from "./excelerate.js";
4
+
5
+ // Objects over `Book`: a workbook hands out sheets, a sheet hands out tables
6
+ // and ranges, and every method that changes something returns its object, so
7
+ // calls chain. Each object is a handle - a sheet index, a table name, an
8
+ // address - and does its work through the `Book` underneath, which stays
9
+ // reachable as `workbook.book` for everything not wrapped here.
10
+ //
11
+ // The build wraps this file for each target (CommonJS for Node, ES modules for
12
+ // the browser and bundlers); it defines `build` and nothing else.
13
+
14
+ function build(Book) {
15
+ const SHEET_ACTIONS = [
16
+ "addDataValidation", "clear", "clearAt", "copyRange", "fillDown", "fillRight",
17
+ "fillSeries", "freezePanes", "insertCells", "insertColumns",
18
+ "insertColumnsMany", "insertRows", "insertRowsMany", "merge", "moveRange",
19
+ "protectSheet", "removeCells", "removeColumns", "removeColumnsMany",
20
+ "removeRows", "removeRowsMany", "set", "setAt", "setCellStyle",
21
+ "setCellStyleAt", "setChartFormat", "setColumnHidden", "setColumnWidth",
22
+ "setComment", "setHyperlink", "setRange", "setRangeAt", "setRangeStyle",
23
+ "setRangeStyles", "setRangeStylesAt", "setRichText", "setRichTextAt",
24
+ "setRowHeight", "setRowHidden", "setShapeFormat", "setSheetVisibility",
25
+ "setShowGridLines", "setZoom", "sortRange", "unprotectSheet",
26
+ ];
27
+ const SHEET_QUERIES = [
28
+ "arrayFormulas", "autoFilter", "cellBold", "cellBoldAt", "cellCount",
29
+ "cellIndent", "cellIndentAt", "cellStyle", "cellStyleAt", "charts",
30
+ "checkValidation", "columnLevel", "columnWidth", "comments",
31
+ "conditionalFormats", "dataValidations", "evaluate", "get", "getAt",
32
+ "getFormatted", "getFormattedAt", "getFormula", "getFormulaAt", "getRange",
33
+ "getRangeAt", "getRangeStyles", "getRangeStylesAt", "getRichText",
34
+ "getRichTextAt", "getRowAt", "goalSeek", "hyperlinks", "imageData", "images",
35
+ "invalidCells", "mergedRanges", "mergedRangesAt", "pivotTables",
36
+ "recalculateCell", "recalculateCellAt", "recalculateFrom", "recalculateFromAt",
37
+ "recalculateFromMany", "removeComment", "removeDuplicates", "removeHyperlink",
38
+ "removeTable", "rowHeight", "rowHidden", "rowLevel", "shapes",
39
+ "sheetProtection", "sheetView", "sheetVisibility", "textToColumns", "toCsv",
40
+ "toHtml", "unmerge", "usedRange", "usedRangeHint", "validationList",
41
+ "verifySheetPassword",
42
+ ];
43
+ const BOOK_ACTIONS = [
44
+ "moveSheet", "protectWorkbook", "registerFunction", "setDefinedName",
45
+ "setDocumentProperties", "setTableFilter", "sortTable", "unprotectWorkbook",
46
+ ];
47
+ const BOOK_QUERIES = [
48
+ "activeSheet", "definedNames", "documentProperties", "externalBooks",
49
+ "registeredFunctions", "removeDefinedName", "sheetIndex", "sheetNames",
50
+ "toOds", "toXls", "unregisterFunction", "workbookProtection",
51
+ ];
52
+
53
+ /** "A" -> 1, "AB" -> 28. */
54
+ const columnNumber = (letters) =>
55
+ [...letters.toUpperCase()].reduce((n, c) => n * 26 + c.charCodeAt(0) - 64, 0);
56
+ /** 1 -> "A", 28 -> "AB". */
57
+ const columnLetters = (n) => {
58
+ let s = "";
59
+ for (; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + ((n - 1) % 26)) + s;
60
+ return s;
61
+ };
62
+ /** "B3" -> { row: 3, column: 2 }. */
63
+ const cell = (address) => {
64
+ const m = /^\$?([A-Za-z]{1,3})\$?(\d+)$/.exec(address.trim());
65
+ if (!m) throw new Error(`not a cell address: ${address}`);
66
+ return { row: Number(m[2]), column: columnNumber(m[1]) };
67
+ };
68
+ const a1 = (row, column) => `${columnLetters(column)}${row}`;
69
+ /** "A1:C6" -> its corners; a single cell is both. */
70
+ const corners = (address) => {
71
+ const [from, to = from] = address.split(":");
72
+ return { start: cell(from), end: cell(to) };
73
+ };
74
+
75
+ class Workbook {
76
+ /** A new workbook, or one over a `Book` already in hand. */
77
+ constructor(book = new Book()) {
78
+ this.book = book;
79
+ // A new Book comes with "Sheet1". The first `addSheet` takes it over
80
+ // instead of leaving an empty sheet in front of the one asked for.
81
+ this._spare = arguments.length === 0;
82
+ }
83
+
84
+ /** Reads xlsx, xls, xlsb, ods, csv and the rest, as `Book.read` does. */
85
+ static read(bytes, name, maxExpanded, onProgress, password) {
86
+ return new Workbook(Book.read(bytes, name, maxExpanded, onProgress, password));
87
+ }
88
+
89
+ /** Reads CSV in a stated shape, as `Book.readCsv` does. */
90
+ static readCsv(bytes, options) {
91
+ return new Workbook(Book.readCsv(bytes, options));
92
+ }
93
+
94
+ /** Hands one sheet over row by row without keeping its grid, as `Book.forEachRow` does. */
95
+ static forEachRow(bytes, name, sheet, callback, formatted) {
96
+ return new Workbook(Book.forEachRow(bytes, name, sheet, callback, formatted));
97
+ }
98
+
99
+ /** A sheet by position or by name. */
100
+ sheet(which) {
101
+ this._spare = false;
102
+ const index = typeof which === "number" ? which : this.book.sheetIndex(which);
103
+ if (index === undefined || index < 0 || index >= this.book.sheetNames().length) {
104
+ throw new Error(`no sheet ${JSON.stringify(which)}`);
105
+ }
106
+ return new Sheet(this, index);
107
+ }
108
+
109
+ /** Every sheet, in tab order. */
110
+ sheets() {
111
+ return this.book.sheetNames().map((_, i) => this.sheet(i));
112
+ }
113
+
114
+ /** Adds a sheet at the end and returns it. */
115
+ addSheet(name = `Sheet${this.book.sheetNames().length + 1}`) {
116
+ if (this._spare) {
117
+ this._spare = false;
118
+ this.book.renameSheet(0, name);
119
+ return new Sheet(this, 0);
120
+ }
121
+ return new Sheet(this, this.book.addSheet(name));
122
+ }
123
+
124
+ /** Recalculates every formula. */
125
+ recalculate(onProgress) {
126
+ this.book.recalculate(undefined, onProgress);
127
+ return this;
128
+ }
129
+
130
+ toXlsx(onProgress) {
131
+ return this.book.toXlsx(onProgress);
132
+ }
133
+
134
+ /** Frees the wasm memory behind the workbook. */
135
+ free() {
136
+ this.book.free();
137
+ }
138
+ }
139
+
140
+ class Sheet {
141
+ constructor(workbook, index) {
142
+ this.workbook = workbook;
143
+ this.index = index;
144
+ }
145
+
146
+ get book() {
147
+ return this.workbook.book;
148
+ }
149
+
150
+ get name() {
151
+ return this.book.sheetNames()[this.index];
152
+ }
153
+
154
+ rename(name) {
155
+ this.book.renameSheet(this.index, name);
156
+ return this;
157
+ }
158
+
159
+ /** What the cell shows, through its number format. */
160
+ text(address) {
161
+ return this.book.getFormatted(this.index, address);
162
+ }
163
+
164
+ /** A block of values whose top left corner lands on `at`. */
165
+ write(at, rows) {
166
+ this.book.setRange(this.index, at, rows);
167
+ return this;
168
+ }
169
+
170
+ /** A range of this sheet: `"A1:C6"`, or one cell. */
171
+ range(address) {
172
+ return new SheetRange(this, address);
173
+ }
174
+
175
+ /** Lays a style patch over every cell of a range. */
176
+ style(address, patch) {
177
+ this.book.setRangeStyle(this.index, address, patch);
178
+ return this;
179
+ }
180
+
181
+ /** Column width in characters; the column is a letter or a number. */
182
+ width(column, characters) {
183
+ const n = typeof column === "number" ? column : columnNumber(column);
184
+ this.book.setColumnWidth(this.index, n, characters);
185
+ return this;
186
+ }
187
+
188
+ /** Freezes the rows above and the columns to the left; zeros unfreeze. */
189
+ freeze(rows, columns = 0) {
190
+ this.book.freezePanes(this.index, rows, columns);
191
+ return this;
192
+ }
193
+
194
+ /** Draws a table over a range already filled; its first row is the header. */
195
+ addTable(name, address, { header = true } = {}) {
196
+ this.book.addTable(this.index, name, address, header);
197
+ return new Table(this, name);
198
+ }
199
+
200
+ /**
201
+ * Writes `rows` from `at` and draws a table over them; the first row is
202
+ * the header.
203
+ */
204
+ addTableFromData(name, at, rows) {
205
+ if (!rows.length || !rows[0].length) throw new Error("a table needs a header row");
206
+ const { row, column } = cell(at);
207
+ const width = Math.max(...rows.map((r) => r.length));
208
+ this.write(at, rows);
209
+ return this.addTable(name, `${at}:${a1(row + rows.length - 1, column + width - 1)}`);
210
+ }
211
+
212
+ /** A table on this sheet, by name. */
213
+ table(name) {
214
+ if (!this.book.tables(this.index).some((t) => t.displayName.toLowerCase() === name.toLowerCase())) {
215
+ throw new Error(`no table ${name} on sheet ${this.name}`);
216
+ }
217
+ return new Table(this, name);
218
+ }
219
+
220
+ tables() {
221
+ return this.book.tables(this.index).map((t) => new Table(this, t.displayName));
222
+ }
223
+
224
+ /** Makes this the sheet a workbook opens on. */
225
+ activate() {
226
+ this.book.setActiveSheet(this.index);
227
+ return this;
228
+ }
229
+
230
+ /** Recalculates the formulas of this sheet. */
231
+ recalculate(onProgress) {
232
+ this.book.recalculate(this.index, onProgress);
233
+ return this;
234
+ }
235
+
236
+ /**
237
+ * Removes the sheet; references to it become `#REF!`. The sheets after
238
+ * it move down an index, so handles to them are stale. Returns the
239
+ * workbook.
240
+ */
241
+ remove() {
242
+ this.book.removeSheet(this.index);
243
+ return this.workbook;
244
+ }
245
+ }
246
+
247
+ class Table {
248
+ constructor(sheet, name) {
249
+ this.sheet = sheet;
250
+ this.name = name;
251
+ }
252
+
253
+ get book() {
254
+ return this.sheet.book;
255
+ }
256
+
257
+ /** What `Book.tables` says about this table. */
258
+ info() {
259
+ const found = this.book
260
+ .tables(this.sheet.index)
261
+ .find((t) => t.displayName.toLowerCase() === this.name.toLowerCase());
262
+ if (!found) throw new Error(`table ${this.name} is gone`);
263
+ return found;
264
+ }
265
+
266
+ get columns() {
267
+ return this.info().columns;
268
+ }
269
+
270
+ /** The whole table, header and totals included, or a range of the sheet. */
271
+ range(address) {
272
+ return address ? this.sheet.range(address) : this.sheet.range(this.info().range);
273
+ }
274
+
275
+ /** The data rows, without the header and totals. */
276
+ data() {
277
+ const { range, headerRowCount, totalsRowCount } = this.info();
278
+ const { start, end } = corners(range);
279
+ const top = start.row + (headerRowCount ?? 1);
280
+ const bottom = end.row - (totalsRowCount ?? 0);
281
+ return this.sheet.range(`${a1(top, start.column)}:${a1(Math.max(top, bottom), end.column)}`);
282
+ }
283
+
284
+ /** The sheet address of a data cell: `row` from 1, `column` a header or a number from 1. */
285
+ address(row, column) {
286
+ const { range, headerRowCount } = this.info();
287
+ const { start } = corners(range);
288
+ const offset = typeof column === "number" ? column - 1 : this.columnIndex(column);
289
+ return a1(start.row + (headerRowCount ?? 1) + row - 1, start.column + offset);
290
+ }
291
+
292
+ columnIndex(header) {
293
+ const i = this.columns.findIndex((c) => c.toLowerCase() === String(header).toLowerCase());
294
+ if (i < 0) throw new Error(`table ${this.name} has no column ${JSON.stringify(header)}`);
295
+ return i;
296
+ }
297
+
298
+ /** Sets one data cell: `table.set(2, "Amount", 340)`. */
299
+ set(row, column, value) {
300
+ this.sheet.set(this.address(row, column), value);
301
+ return this;
302
+ }
303
+
304
+ get(row, column) {
305
+ return this.sheet.get(this.address(row, column));
306
+ }
307
+
308
+ /** Filters by a column and hides the rows that fail, as Excel does. */
309
+ addFilter(column, criteria) {
310
+ this.book.setTableFilter(this.name, column, criteria);
311
+ return this;
312
+ }
313
+
314
+ /** Takes the criterion off one column, or off all of them. */
315
+ clearFilter(column) {
316
+ const columns = column === undefined ? this.columns : [column];
317
+ for (const c of columns) this.book.setTableFilter(this.name, c, null);
318
+ return this;
319
+ }
320
+
321
+ /** Sorts the data rows: `["Region", "-Amount"]`, a minus for largest first. */
322
+ sort(keys) {
323
+ this.book.sortTable(this.name, keys);
324
+ return this;
325
+ }
326
+
327
+ /**
328
+ * The data rows as objects keyed by header. `{ visible: true }` leaves
329
+ * out the rows a filter hides.
330
+ */
331
+ records({ visible = false } = {}) {
332
+ const columns = this.columns;
333
+ const data = this.data();
334
+ const rows = visible ? data.visibleValues() : data.values();
335
+ return rows.map((r) => Object.fromEntries(columns.map((c, i) => [c, r[i]])));
336
+ }
337
+ }
338
+
339
+ class SheetRange {
340
+ constructor(sheet, address) {
341
+ this.sheet = sheet;
342
+ this.address = address;
343
+ }
344
+
345
+ get book() {
346
+ return this.sheet.book;
347
+ }
348
+
349
+ /** The values, a row per array. */
350
+ values() {
351
+ return this.book.getRange(this.sheet.index, this.address);
352
+ }
353
+
354
+ /** The values of the rows a filter or a user has not hidden. */
355
+ visibleValues() {
356
+ const { start } = corners(this.address);
357
+ return this.values().filter((_, i) => !this.sheet.rowHidden(start.row + i));
358
+ }
359
+
360
+ /** Writes a block from the top left corner of the range. */
361
+ set(rows) {
362
+ this.sheet.write(this.address.split(":")[0], rows);
363
+ return this;
364
+ }
365
+
366
+ style(patch) {
367
+ this.sheet.style(this.address, patch);
368
+ return this;
369
+ }
370
+
371
+ merge() {
372
+ this.book.merge(this.sheet.index, this.address);
373
+ return this;
374
+ }
375
+ }
376
+
377
+ // Every Book method that takes the sheet first is a Sheet method without
378
+ // it, and every one that takes no sheet a Workbook method. What Book
379
+ // answers with nothing returns the object, so it chains; the rest return
380
+ // the answer. The lists follow Book's declarations; a test in npm/test.js
381
+ // fails when Book gains a method neither covers.
382
+ const delegate = (target, names, chain, args) => {
383
+ for (const name of names) {
384
+ Object.defineProperty(target.prototype, name, {
385
+ configurable: true,
386
+ writable: true,
387
+ value: chain
388
+ ? function (...rest) {
389
+ this.book[name](...args(this), ...rest);
390
+ return this;
391
+ }
392
+ : function (...rest) {
393
+ return this.book[name](...args(this), ...rest);
394
+ },
395
+ });
396
+ }
397
+ };
398
+ const onSheet = (sheet) => [sheet.index];
399
+ const onBook = () => [];
400
+ delegate(Sheet, SHEET_ACTIONS, true, onSheet);
401
+ delegate(Sheet, SHEET_QUERIES, false, onSheet);
402
+ delegate(Workbook, BOOK_ACTIONS, true, onBook);
403
+ delegate(Workbook, BOOK_QUERIES, false, onBook);
404
+
405
+ return { Workbook, Sheet, Table, SheetRange };
406
+ }
407
+
408
+ export const { Workbook, Sheet, Table, SheetRange } = build(core.Book);
@@ -0,0 +1,4 @@
1
+ {
2
+ "type": "module",
3
+ "sideEffects": false
4
+ }