@20baht/export 0.1.1 → 0.1.2

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`). 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/sheet.d.ts CHANGED
@@ -30,19 +30,32 @@ export interface Sheet<Row> {
30
30
  /** How a laid-out cell looks in a workbook. */
31
31
  export interface CellLook {
32
32
  bold?: boolean;
33
+ italic?: boolean;
34
+ underline?: boolean;
35
+ /** The text's colour, `#rrggbb`. */
36
+ color?: string;
33
37
  /** A light grey fill: a header, a band. */
34
38
  shade?: boolean;
39
+ /** A fill of this colour, `#rrggbb`; it wins over `shade`. */
40
+ fill?: string;
35
41
  /** A thin line on every side. */
36
42
  border?: boolean;
37
43
  /** Long text breaks onto more lines instead of running over the next cell. */
38
44
  wrap?: boolean;
39
45
  center?: boolean;
46
+ /** Across only: left, centre or right. It wins over `center`'s across; up and down stays as it is. */
47
+ align?: 'left' | 'center' | 'right';
40
48
  /** An Excel number format for a number or a date: `'#,##0.00'`, `'dd/mm/yyyy hh:mm'`. */
41
49
  format?: string;
42
50
  }
43
- /** A cell of a laid-out sheet: its value alone, or with how it looks. */
51
+ /**
52
+ * A cell of a laid-out sheet: its value alone, or with how it looks. With `formula` (Excel's own
53
+ * spelling, without its `=`), the cell is that formula and `value` is what it had when the file was
54
+ * written: whoever opens the workbook works it out again.
55
+ */
44
56
  export type LaidCell = Cell | ({
45
57
  value: Cell;
58
+ formula?: string;
46
59
  } & CellLook);
47
60
  /** Cells shown as one: from `row` and `column` (both from 0), `rows` down and `columns` across (1 when unset). */
48
61
  export interface CellMerge {
package/dist/xlsx.js CHANGED
@@ -28,7 +28,14 @@ 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>`;
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
+ };
32
39
  const THIN = ['left', 'right', 'top', 'bottom']
33
40
  .map((side) => `<${side} style="thin"><color auto="1"/></${side}>`)
34
41
  .join('');
@@ -36,7 +43,8 @@ class Styles {
36
43
  #formats = new Map();
37
44
  #looks = new Map();
38
45
  #xfs = [];
39
- #shaded = false;
46
+ #fonts = new Map();
47
+ #fills = new Map();
40
48
  #bordered = false;
41
49
  of(format) {
42
50
  return this.look({ ...(format === undefined ? {} : { format }) });
@@ -46,7 +54,14 @@ class Styles {
46
54
  const flags = [look.bold, look.shade, look.border, look.wrap, look.center]
47
55
  .map((on) => (on === true ? '1' : '0'))
48
56
  .join('');
49
- const key = flags + (format ?? '');
57
+ const more = [
58
+ look.italic === true ? 'i' : '',
59
+ look.underline === true ? 'u' : '',
60
+ look.color ?? '',
61
+ look.fill ?? '',
62
+ look.align ?? '',
63
+ ].join('|');
64
+ const key = flags + (more === '||||' ? '' : `${more}|`) + (format ?? '');
50
65
  if (key === '00000')
51
66
  return 0;
52
67
  if (key === '10000')
@@ -69,22 +84,52 @@ class Styles {
69
84
  }
70
85
  return 164 + at;
71
86
  }
87
+ #font(look) {
88
+ const parts = (look.bold === true ? '<b/>' : '') +
89
+ (look.italic === true ? '<i/>' : '') +
90
+ (look.underline === true ? '<u/>' : '') +
91
+ (look.color === undefined ? '' : `<color rgb="FF${rgb(look.color)}"/>`);
92
+ if (parts === '')
93
+ return 0;
94
+ if (parts === '<b/>')
95
+ return 1;
96
+ let at = this.#fonts.get(parts);
97
+ if (at === undefined) {
98
+ at = this.#fonts.size + 2;
99
+ this.#fonts.set(parts, at);
100
+ }
101
+ return at;
102
+ }
103
+ #fill(look) {
104
+ const colour = look.fill === undefined ? (look.shade === true ? SHADE : null) : rgb(look.fill);
105
+ if (colour === null)
106
+ return 0;
107
+ let at = this.#fills.get(colour);
108
+ if (at === undefined) {
109
+ at = this.#fills.size + 2;
110
+ this.#fills.set(colour, at);
111
+ }
112
+ return at;
113
+ }
72
114
  #xf(look, format) {
73
115
  const on = (flag, text) => (flag === true ? text : '');
74
- this.#shaded ||= look.shade === true;
75
116
  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"` +
117
+ const font = this.#font(look);
118
+ const fill = this.#fill(look);
119
+ const across = look.align ?? (look.center === true ? 'center' : undefined);
120
+ const upDown = look.wrap === true || look.center === true;
121
+ const aligned = upDown || across !== undefined;
122
+ const attrs = `numFmtId="${String(this.#numFmt(format))}" fontId="${String(font)}"` +
123
+ ` fillId="${String(fill)}" borderId="${on(look.border, '1') || '0'}" xfId="0"` +
79
124
  on(format !== undefined, ' applyNumberFormat="1"') +
80
- on(look.bold, ' applyFont="1"') +
81
- on(look.shade, ' applyFill="1"') +
125
+ on(font !== 0, ' applyFont="1"') +
126
+ on(fill !== 0, ' applyFill="1"') +
82
127
  on(look.border, ' applyBorder="1"') +
83
128
  on(aligned, ' applyAlignment="1"');
84
129
  if (!aligned)
85
130
  return `<xf ${attrs}/>`;
86
- const alignment = on(look.center, ' horizontal="center"') +
87
- ` vertical="${on(look.center, 'center') || 'top'}"` +
131
+ const alignment = (across === undefined ? '' : ` horizontal="${across}"`) +
132
+ on(upDown, ` vertical="${on(look.center, 'center') || 'top'}"`) +
88
133
  on(look.wrap, ' wrapText="1"');
89
134
  return `<xf ${attrs}><alignment${alignment}/></xf>`;
90
135
  }
@@ -96,8 +141,16 @@ class Styles {
96
141
  .join('')}</numFmts>`
97
142
  : '';
98
143
  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>` +
144
+ `<fonts count="${String(this.#fonts.size + 2)}"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font>${[
145
+ ...this.#fonts.keys(),
146
+ ]
147
+ .map((parts) => `<font>${parts}<sz val="11"/><name val="Calibri"/></font>`)
148
+ .join('')}</fonts>` +
149
+ `<fills count="${String(this.#fills.size + 2)}"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>${[
150
+ ...this.#fills.keys(),
151
+ ]
152
+ .map((colour) => `<fill><patternFill patternType="solid"><fgColor rgb="FF${colour}"/><bgColor indexed="64"/></patternFill></fill>`)
153
+ .join('')}</fills>` +
101
154
  `<borders count="${this.#bordered ? '2' : '1'}"><border><left/><right/><top/><bottom/><diagonal/></border>${this.#bordered ? `<border>${THIN}<diagonal/></border>` : ''}</borders>` +
102
155
  `<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>` +
103
156
  `<cellXfs count="${String(this.#xfs.length + 2)}"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>` +
@@ -124,9 +177,11 @@ const styleOf = (cell, plan, styles, look) => {
124
177
  const { format: _format, ...bare } = look;
125
178
  return styles.look(bare);
126
179
  };
127
- const cellXml = (cell, ref, plan, styles, timeZone, look) => {
180
+ const cellXml = (cell, ref, plan, styles, timeZone, look, formula) => {
128
181
  const index = styleOf(cell, plan, styles, look);
129
182
  const s = index ? ` s="${String(index)}"` : '';
183
+ if (formula !== undefined)
184
+ return formulaXml(formula, cell, ref, s, timeZone);
130
185
  if (cell === null || cell === undefined || cell === '')
131
186
  return s ? `<c r="${ref}"${s}/>` : '';
132
187
  if (typeof cell === 'number') {
@@ -143,6 +198,22 @@ const cellXml = (cell, ref, plan, styles, timeZone, look) => {
143
198
  throw new RangeError(`cell ${ref} holds ${String(cell.length)} characters; a workbook cell holds at most ${String(MAX_TEXT)}`);
144
199
  return `<c r="${ref}"${s} t="inlineStr"><is><t xml:space="preserve">${escaped(cell)}</t></is></c>`;
145
200
  };
201
+ const formulaXml = (formula, cached, ref, s, timeZone) => {
202
+ const text = formula.startsWith('=') ? formula.slice(1) : formula;
203
+ if (text === '' || text.length > MAX_FORMULA)
204
+ throw new RangeError(`cell ${ref}: a formula holds 1 to ${String(MAX_FORMULA)} characters after its =`);
205
+ const f = `<f>${escaped(text)}</f>`;
206
+ if (typeof cached === 'boolean')
207
+ return `<c r="${ref}"${s} t="b">${f}<v>${cached ? '1' : '0'}</v></c>`;
208
+ if (typeof cached === 'string' && cached !== '')
209
+ return `<c r="${ref}"${s} t="str">${f}<v>${escaped(cached.slice(0, MAX_TEXT))}</v></c>`;
210
+ const number = cached instanceof Date && !Number.isNaN(cached.getTime())
211
+ ? serialDate(cached, timeZone)
212
+ : cached;
213
+ return typeof number === 'number' && Number.isFinite(number)
214
+ ? `<c r="${ref}"${s}>${f}<v>${String(number)}</v></c>`
215
+ : `<c r="${ref}"${s}>${f}</c>`;
216
+ };
146
217
  const MEASURED_ROWS = 200;
147
218
  const shownWidth = (cell) => {
148
219
  if (cell === null || cell === undefined)
@@ -214,10 +285,12 @@ const laidXml = (sheet, styles, timeZone) => {
214
285
  if (row.length > MAX_COLUMNS)
215
286
  throw new RangeError(`a sheet has at most ${String(MAX_COLUMNS)} columns`);
216
287
  const cells = row.map((cell, c) => {
217
- const { value, ...look } = isLooked(cell) ? cell : { value: cell };
288
+ const { value, formula, ...look } = isLooked(cell)
289
+ ? cell
290
+ : { value: cell, formula: undefined };
218
291
  if (!across.has(`${String(r)}:${String(c)}`))
219
292
  measured[c] = Math.max(measured[c] ?? 0, shownWidth(value));
220
- return cellXml(value, `${columnName(c)}${String(r + 1)}`, { numberStyle: 0 }, styles, timeZone, look);
293
+ return cellXml(value, `${columnName(c)}${String(r + 1)}`, { numberStyle: 0 }, styles, timeZone, look, formula);
221
294
  });
222
295
  return `<row r="${String(r + 1)}">${cells.join('')}</row>`;
223
296
  });
@@ -303,7 +376,9 @@ export const xlsx = async (sheets, options = {}) => {
303
376
  ids
304
377
  .map((id, i) => `<sheet name="${escaped(names[i] ?? '')}" sheetId="${id}" r:id="rId${id}"/>`)
305
378
  .join('') +
306
- `</sheets></workbook>`),
379
+ `</sheets>` +
380
+ (parts.some((part) => part.includes('<f>')) ? `<calcPr fullCalcOnLoad="1"/>` : '') +
381
+ `</workbook>`),
307
382
  file('xl/_rels/workbook.xml.rels', `${XML}<Relationships xmlns="${PKG}/relationships">` +
308
383
  ids
309
384
  .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.2",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"