@20baht/export 0.1.1 → 0.1.3

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
@@ -78,7 +78,8 @@ const two = await xlsx([income, expenses]); // a tab per sheet
78
78
  - Past Excel's limits (1,048,576 rows, 16,384 columns, 32,767 characters in a cell) it throws a `RangeError`
79
79
  naming the cell, rather than write a file Excel cannot open.
80
80
 
81
- It is a writer for reports and exports, not a spreadsheet library: no formulas, merged cells, colours or charts.
81
+ It is a writer for reports and exports, not a spreadsheet library: it works no formula out and draws no chart.
82
+ A laid-out sheet (below) carries merged cells, colours and formulas written as text.
82
83
 
83
84
  ## A document, cell by cell
84
85
 
@@ -109,7 +110,10 @@ const page: LaidSheet = {
109
110
  const bytes = await xlsx([page, expenses]); // beside sheets of rows, a tab each
110
111
  ```
111
112
 
112
- A cell is its value (`string | number | boolean | Date | null`) or `{ value, bold, shade, border, wrap, center, format }`.
113
+ A cell is its value (`string | number | boolean | Date | null`) or `{ value, bold, italic, underline, color, shade, fill, border, wrap, center, align, format }`
114
+ (`color` and `fill` as `#rrggbb`; `align` is `left` / `center` / `right`; `border` is `true` or the sides, `['top', 'bottom']`). With `formula` (Excel's spelling, `SUM(A1:A9)`), the cell is
115
+ that formula and `value` is what it had when the file was written: the workbook asks its reader to work it out again.
116
+ `@20baht/spreadsheet`'s `bookWorkbook` lays a book out this way.
113
117
  `@20baht/sheet`'s `sheetWorkbook(sheet, data)` lays a filled sheet out this way.
114
118
 
115
119
  ## A table's columns
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { csv, csvStream, CSV_TYPE, type CsvOptions } from './csv.js';
2
2
  export { contentDisposition, contentTypeOf, download } from './download.js';
3
- export type { Cell, CellLook, CellMerge, Column, LaidCell, LaidSheet, Sheet, SyncSheet, } from './sheet.js';
3
+ export type { Cell, BorderSide, CellLook, CellMerge, Column, LaidCell, LaidSheet, Sheet, SyncSheet, } from './sheet.js';
4
4
  export { tableColumns, type TableColumnLike, type TableColumnsOptions, type TableLike, } from './table.js';
5
5
  export { columnName, xlsx, XLSX_TYPE, type XlsxOptions } from './xlsx.js';
package/dist/sheet.d.ts CHANGED
@@ -28,21 +28,36 @@ export interface Sheet<Row> {
28
28
  rows: Iterable<Row> | AsyncIterable<Row>;
29
29
  }
30
30
  /** How a laid-out cell looks in a workbook. */
31
+ /** A side of a cell a line can be drawn on. */
32
+ export type BorderSide = 'left' | 'right' | 'top' | 'bottom';
31
33
  export interface CellLook {
32
34
  bold?: boolean;
35
+ italic?: boolean;
36
+ underline?: boolean;
37
+ /** The text's colour, `#rrggbb`. */
38
+ color?: string;
33
39
  /** A light grey fill: a header, a band. */
34
40
  shade?: boolean;
35
- /** A thin line on every side. */
36
- border?: boolean;
41
+ /** A fill of this colour, `#rrggbb`; it wins over `shade`. */
42
+ fill?: string;
43
+ /** A thin line on every side, or on the sides named. */
44
+ border?: boolean | readonly BorderSide[];
37
45
  /** Long text breaks onto more lines instead of running over the next cell. */
38
46
  wrap?: boolean;
39
47
  center?: boolean;
48
+ /** Across only: left, centre or right. It wins over `center`'s across; up and down stays as it is. */
49
+ align?: 'left' | 'center' | 'right';
40
50
  /** An Excel number format for a number or a date: `'#,##0.00'`, `'dd/mm/yyyy hh:mm'`. */
41
51
  format?: string;
42
52
  }
43
- /** A cell of a laid-out sheet: its value alone, or with how it looks. */
53
+ /**
54
+ * A cell of a laid-out sheet: its value alone, or with how it looks. With `formula` (Excel's own
55
+ * spelling, without its `=`), the cell is that formula and `value` is what it had when the file was
56
+ * written: whoever opens the workbook works it out again.
57
+ */
44
58
  export type LaidCell = Cell | ({
45
59
  value: Cell;
60
+ formula?: string;
46
61
  } & CellLook);
47
62
  /** Cells shown as one: from `row` and `column` (both from 0), `rows` down and `columns` across (1 when unset). */
48
63
  export interface CellMerge {
package/dist/xlsx.js CHANGED
@@ -28,16 +28,25 @@ const textWidth = (text) => {
28
28
  }
29
29
  return width;
30
30
  };
31
- const SOLID = `<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/><bgColor indexed="64"/></patternFill></fill>`;
32
- const THIN = ['left', 'right', 'top', 'bottom']
33
- .map((side) => `<${side} style="thin"><color auto="1"/></${side}>`)
34
- .join('');
31
+ const SHADE = 'E7E6E6';
32
+ const COLOUR = /^#[0-9a-fA-F]{6}$/;
33
+ const MAX_FORMULA = 8192;
34
+ const rgb = (colour) => {
35
+ if (!COLOUR.test(colour))
36
+ throw new RangeError(`a colour is written #rrggbb, not ${colour}`);
37
+ return colour.slice(1).toUpperCase();
38
+ };
39
+ const SIDES = ['left', 'right', 'top', 'bottom'];
40
+ const sidesOf = (border) => border === true
41
+ ? SIDES.join(',')
42
+ : SIDES.filter((side) => border !== undefined && border !== false && border.includes(side)).join(',');
35
43
  class Styles {
36
44
  #formats = new Map();
37
45
  #looks = new Map();
38
46
  #xfs = [];
39
- #shaded = false;
40
- #bordered = false;
47
+ #fonts = new Map();
48
+ #fills = new Map();
49
+ #borders = new Map();
41
50
  of(format) {
42
51
  return this.look({ ...(format === undefined ? {} : { format }) });
43
52
  }
@@ -46,7 +55,15 @@ class Styles {
46
55
  const flags = [look.bold, look.shade, look.border, look.wrap, look.center]
47
56
  .map((on) => (on === true ? '1' : '0'))
48
57
  .join('');
49
- const key = flags + (format ?? '');
58
+ const more = [
59
+ look.italic === true ? 'i' : '',
60
+ look.underline === true ? 'u' : '',
61
+ look.color ?? '',
62
+ look.fill ?? '',
63
+ look.align ?? '',
64
+ look.border === true ? '' : sidesOf(look.border),
65
+ ].join('|');
66
+ const key = flags + (more === '|||||' ? '' : `${more}|`) + (format ?? '');
50
67
  if (key === '00000')
51
68
  return 0;
52
69
  if (key === '10000')
@@ -69,22 +86,63 @@ class Styles {
69
86
  }
70
87
  return 164 + at;
71
88
  }
89
+ #font(look) {
90
+ const parts = (look.bold === true ? '<b/>' : '') +
91
+ (look.italic === true ? '<i/>' : '') +
92
+ (look.underline === true ? '<u/>' : '') +
93
+ (look.color === undefined ? '' : `<color rgb="FF${rgb(look.color)}"/>`);
94
+ if (parts === '')
95
+ return 0;
96
+ if (parts === '<b/>')
97
+ return 1;
98
+ let at = this.#fonts.get(parts);
99
+ if (at === undefined) {
100
+ at = this.#fonts.size + 2;
101
+ this.#fonts.set(parts, at);
102
+ }
103
+ return at;
104
+ }
105
+ #fill(look) {
106
+ const colour = look.fill === undefined ? (look.shade === true ? SHADE : null) : rgb(look.fill);
107
+ if (colour === null)
108
+ return 0;
109
+ let at = this.#fills.get(colour);
110
+ if (at === undefined) {
111
+ at = this.#fills.size + 2;
112
+ this.#fills.set(colour, at);
113
+ }
114
+ return at;
115
+ }
116
+ #border(look) {
117
+ const sides = sidesOf(look.border);
118
+ if (sides === '')
119
+ return 0;
120
+ let at = this.#borders.get(sides);
121
+ if (at === undefined) {
122
+ at = this.#borders.size + 1;
123
+ this.#borders.set(sides, at);
124
+ }
125
+ return at;
126
+ }
72
127
  #xf(look, format) {
73
128
  const on = (flag, text) => (flag === true ? text : '');
74
- this.#shaded ||= look.shade === true;
75
- this.#bordered ||= look.border === true;
76
- const aligned = look.wrap === true || look.center === true;
77
- const attrs = `numFmtId="${String(this.#numFmt(format))}" fontId="${on(look.bold, '1') || '0'}"` +
78
- ` fillId="${on(look.shade, '2') || '0'}" borderId="${on(look.border, '1') || '0'}" xfId="0"` +
129
+ const border = this.#border(look);
130
+ const font = this.#font(look);
131
+ const fill = this.#fill(look);
132
+ const across = look.align ?? (look.center === true ? 'center' : undefined);
133
+ const upDown = look.wrap === true || look.center === true;
134
+ const aligned = upDown || across !== undefined;
135
+ const attrs = `numFmtId="${String(this.#numFmt(format))}" fontId="${String(font)}"` +
136
+ ` fillId="${String(fill)}" borderId="${String(border)}" xfId="0"` +
79
137
  on(format !== undefined, ' applyNumberFormat="1"') +
80
- on(look.bold, ' applyFont="1"') +
81
- on(look.shade, ' applyFill="1"') +
82
- on(look.border, ' applyBorder="1"') +
138
+ on(font !== 0, ' applyFont="1"') +
139
+ on(fill !== 0, ' applyFill="1"') +
140
+ on(border !== 0, ' applyBorder="1"') +
83
141
  on(aligned, ' applyAlignment="1"');
84
142
  if (!aligned)
85
143
  return `<xf ${attrs}/>`;
86
- const alignment = on(look.center, ' horizontal="center"') +
87
- ` vertical="${on(look.center, 'center') || 'top'}"` +
144
+ const alignment = (across === undefined ? '' : ` horizontal="${across}"`) +
145
+ on(upDown, ` vertical="${on(look.center, 'center') || 'top'}"`) +
88
146
  on(look.wrap, ' wrapText="1"');
89
147
  return `<xf ${attrs}><alignment${alignment}/></xf>`;
90
148
  }
@@ -96,9 +154,23 @@ class Styles {
96
154
  .join('')}</numFmts>`
97
155
  : '';
98
156
  return (`${XML}<styleSheet xmlns="${MAIN}">${numFmts}` +
99
- `<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts>` +
100
- `<fills count="${this.#shaded ? '3' : '2'}"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>${this.#shaded ? SOLID : ''}</fills>` +
101
- `<borders count="${this.#bordered ? '2' : '1'}"><border><left/><right/><top/><bottom/><diagonal/></border>${this.#bordered ? `<border>${THIN}<diagonal/></border>` : ''}</borders>` +
157
+ `<fonts count="${String(this.#fonts.size + 2)}"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font>${[
158
+ ...this.#fonts.keys(),
159
+ ]
160
+ .map((parts) => `<font>${parts}<sz val="11"/><name val="Calibri"/></font>`)
161
+ .join('')}</fonts>` +
162
+ `<fills count="${String(this.#fills.size + 2)}"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>${[
163
+ ...this.#fills.keys(),
164
+ ]
165
+ .map((colour) => `<fill><patternFill patternType="solid"><fgColor rgb="FF${colour}"/><bgColor indexed="64"/></patternFill></fill>`)
166
+ .join('')}</fills>` +
167
+ `<borders count="${String(this.#borders.size + 1)}"><border><left/><right/><top/><bottom/><diagonal/></border>${[
168
+ ...this.#borders.keys(),
169
+ ]
170
+ .map((sides) => `<border>${SIDES.map((side) => sides.split(',').includes(side)
171
+ ? `<${side} style="thin"><color auto="1"/></${side}>`
172
+ : `<${side}/>`).join('')}<diagonal/></border>`)
173
+ .join('')}</borders>` +
102
174
  `<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>` +
103
175
  `<cellXfs count="${String(this.#xfs.length + 2)}"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>` +
104
176
  `<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>${this.#xfs.join('')}</cellXfs>` +
@@ -124,9 +196,11 @@ const styleOf = (cell, plan, styles, look) => {
124
196
  const { format: _format, ...bare } = look;
125
197
  return styles.look(bare);
126
198
  };
127
- const cellXml = (cell, ref, plan, styles, timeZone, look) => {
199
+ const cellXml = (cell, ref, plan, styles, timeZone, look, formula) => {
128
200
  const index = styleOf(cell, plan, styles, look);
129
201
  const s = index ? ` s="${String(index)}"` : '';
202
+ if (formula !== undefined)
203
+ return formulaXml(formula, cell, ref, s, timeZone);
130
204
  if (cell === null || cell === undefined || cell === '')
131
205
  return s ? `<c r="${ref}"${s}/>` : '';
132
206
  if (typeof cell === 'number') {
@@ -143,6 +217,22 @@ const cellXml = (cell, ref, plan, styles, timeZone, look) => {
143
217
  throw new RangeError(`cell ${ref} holds ${String(cell.length)} characters; a workbook cell holds at most ${String(MAX_TEXT)}`);
144
218
  return `<c r="${ref}"${s} t="inlineStr"><is><t xml:space="preserve">${escaped(cell)}</t></is></c>`;
145
219
  };
220
+ const formulaXml = (formula, cached, ref, s, timeZone) => {
221
+ const text = formula.startsWith('=') ? formula.slice(1) : formula;
222
+ if (text === '' || text.length > MAX_FORMULA)
223
+ throw new RangeError(`cell ${ref}: a formula holds 1 to ${String(MAX_FORMULA)} characters after its =`);
224
+ const f = `<f>${escaped(text)}</f>`;
225
+ if (typeof cached === 'boolean')
226
+ return `<c r="${ref}"${s} t="b">${f}<v>${cached ? '1' : '0'}</v></c>`;
227
+ if (typeof cached === 'string' && cached !== '')
228
+ return `<c r="${ref}"${s} t="str">${f}<v>${escaped(cached.slice(0, MAX_TEXT))}</v></c>`;
229
+ const number = cached instanceof Date && !Number.isNaN(cached.getTime())
230
+ ? serialDate(cached, timeZone)
231
+ : cached;
232
+ return typeof number === 'number' && Number.isFinite(number)
233
+ ? `<c r="${ref}"${s}>${f}<v>${String(number)}</v></c>`
234
+ : `<c r="${ref}"${s}>${f}</c>`;
235
+ };
146
236
  const MEASURED_ROWS = 200;
147
237
  const shownWidth = (cell) => {
148
238
  if (cell === null || cell === undefined)
@@ -214,10 +304,12 @@ const laidXml = (sheet, styles, timeZone) => {
214
304
  if (row.length > MAX_COLUMNS)
215
305
  throw new RangeError(`a sheet has at most ${String(MAX_COLUMNS)} columns`);
216
306
  const cells = row.map((cell, c) => {
217
- const { value, ...look } = isLooked(cell) ? cell : { value: cell };
307
+ const { value, formula, ...look } = isLooked(cell)
308
+ ? cell
309
+ : { value: cell, formula: undefined };
218
310
  if (!across.has(`${String(r)}:${String(c)}`))
219
311
  measured[c] = Math.max(measured[c] ?? 0, shownWidth(value));
220
- return cellXml(value, `${columnName(c)}${String(r + 1)}`, { numberStyle: 0 }, styles, timeZone, look);
312
+ return cellXml(value, `${columnName(c)}${String(r + 1)}`, { numberStyle: 0 }, styles, timeZone, look, formula);
221
313
  });
222
314
  return `<row r="${String(r + 1)}">${cells.join('')}</row>`;
223
315
  });
@@ -303,7 +395,9 @@ export const xlsx = async (sheets, options = {}) => {
303
395
  ids
304
396
  .map((id, i) => `<sheet name="${escaped(names[i] ?? '')}" sheetId="${id}" r:id="rId${id}"/>`)
305
397
  .join('') +
306
- `</sheets></workbook>`),
398
+ `</sheets>` +
399
+ (parts.some((part) => part.includes('<f>')) ? `<calcPr fullCalcOnLoad="1"/>` : '') +
400
+ `</workbook>`),
307
401
  file('xl/_rels/workbook.xml.rels', `${XML}<Relationships xmlns="${PKG}/relationships">` +
308
402
  ids
309
403
  .map((id) => `<Relationship Id="rId${id}" Type="${REL}/worksheet" Target="worksheets/sheet${id}.xml"/>`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@20baht/export",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"