@20baht/export 0.1.0 → 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 +37 -1
- package/dist/index.d.ts +1 -1
- package/dist/sheet.d.ts +52 -0
- package/dist/xlsx.d.ts +5 -4
- package/dist/xlsx.js +206 -26
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -78,7 +78,43 @@ 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
|
|
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.
|
|
83
|
+
|
|
84
|
+
## A document, cell by cell
|
|
85
|
+
|
|
86
|
+
A list is rows under a header. A document (a checklist, a form to hand in) is cells put where they belong: a
|
|
87
|
+
`LaidSheet`. A workbook only; `csv()` does not take one.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { xlsx, type LaidSheet } from '@20baht/export';
|
|
91
|
+
|
|
92
|
+
const head = { bold: true, shade: true, border: true, center: true };
|
|
93
|
+
const page: LaidSheet = {
|
|
94
|
+
name: 'Checklist',
|
|
95
|
+
cells: [
|
|
96
|
+
[{ value: 'Deployment Checklist', bold: true }],
|
|
97
|
+
[],
|
|
98
|
+
[{ value: 'No.', ...head }, { value: 'Plan', ...head }, { value: null, ...head }],
|
|
99
|
+
[{ value: null, ...head }, { value: 'Start', ...head }, { value: 'Finish', ...head }],
|
|
100
|
+
[{ value: 1, border: true }, { value: new Date(Date.UTC(2026, 10, 19, 13)), format: 'dd/mm/yyyy hh:mm', border: true }],
|
|
101
|
+
],
|
|
102
|
+
merges: [
|
|
103
|
+
{ row: 0, column: 0, columns: 3 }, // the title across the table
|
|
104
|
+
{ row: 2, column: 1, columns: 2 }, // "Plan" over Start and Finish
|
|
105
|
+
{ row: 2, column: 0, rows: 2 }, // "No." down both header rows
|
|
106
|
+
],
|
|
107
|
+
widths: [6, 18, 18], // characters; unset: what the column holds, merged cells aside
|
|
108
|
+
frozen: 4, // rows kept in view
|
|
109
|
+
};
|
|
110
|
+
const bytes = await xlsx([page, expenses]); // beside sheets of rows, a tab each
|
|
111
|
+
```
|
|
112
|
+
|
|
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.
|
|
117
|
+
`@20baht/sheet`'s `sheetWorkbook(sheet, data)` lays a filled sheet out this way.
|
|
82
118
|
|
|
83
119
|
## A table's columns
|
|
84
120
|
|
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, Column, Sheet, SyncSheet } from './sheet.js';
|
|
3
|
+
export type { Cell, 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
|
@@ -27,6 +27,58 @@ export interface Sheet<Row> {
|
|
|
27
27
|
/** An array, any iterable, or an async iterable (a query read page by page). */
|
|
28
28
|
rows: Iterable<Row> | AsyncIterable<Row>;
|
|
29
29
|
}
|
|
30
|
+
/** How a laid-out cell looks in a workbook. */
|
|
31
|
+
export interface CellLook {
|
|
32
|
+
bold?: boolean;
|
|
33
|
+
italic?: boolean;
|
|
34
|
+
underline?: boolean;
|
|
35
|
+
/** The text's colour, `#rrggbb`. */
|
|
36
|
+
color?: string;
|
|
37
|
+
/** A light grey fill: a header, a band. */
|
|
38
|
+
shade?: boolean;
|
|
39
|
+
/** A fill of this colour, `#rrggbb`; it wins over `shade`. */
|
|
40
|
+
fill?: string;
|
|
41
|
+
/** A thin line on every side. */
|
|
42
|
+
border?: boolean;
|
|
43
|
+
/** Long text breaks onto more lines instead of running over the next cell. */
|
|
44
|
+
wrap?: boolean;
|
|
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';
|
|
48
|
+
/** An Excel number format for a number or a date: `'#,##0.00'`, `'dd/mm/yyyy hh:mm'`. */
|
|
49
|
+
format?: string;
|
|
50
|
+
}
|
|
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
|
+
*/
|
|
56
|
+
export type LaidCell = Cell | ({
|
|
57
|
+
value: Cell;
|
|
58
|
+
formula?: string;
|
|
59
|
+
} & CellLook);
|
|
60
|
+
/** Cells shown as one: from `row` and `column` (both from 0), `rows` down and `columns` across (1 when unset). */
|
|
61
|
+
export interface CellMerge {
|
|
62
|
+
row: number;
|
|
63
|
+
column: number;
|
|
64
|
+
rows?: number;
|
|
65
|
+
columns?: number;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* A sheet laid out cell by cell, for a document rather than a list: a title, labelled values, a
|
|
69
|
+
* table with a two-row header and bands across it. A workbook only; `csv()` does not take it.
|
|
70
|
+
*/
|
|
71
|
+
export interface LaidSheet {
|
|
72
|
+
/** The tab's name in a workbook. Unset: `Sheet1`, `Sheet2`, … */
|
|
73
|
+
name?: string;
|
|
74
|
+
/** The rows, top to bottom; a row is its cells, left to right. */
|
|
75
|
+
cells: readonly (readonly LaidCell[])[];
|
|
76
|
+
merges?: readonly CellMerge[];
|
|
77
|
+
/** Column widths in characters. Unset: as wide as what the column holds (8 to 60), merged cells aside. */
|
|
78
|
+
widths?: readonly (number | undefined)[];
|
|
79
|
+
/** How many rows from the top stay in view. */
|
|
80
|
+
frozen?: number;
|
|
81
|
+
}
|
|
30
82
|
/** A sheet whose rows are all at hand: what `csv()` takes. */
|
|
31
83
|
export interface SyncSheet<Row> extends Sheet<Row> {
|
|
32
84
|
rows: Iterable<Row>;
|
package/dist/xlsx.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Sheet } from './sheet.js';
|
|
1
|
+
import { type LaidSheet, type Sheet } from './sheet.js';
|
|
2
2
|
export interface XlsxOptions {
|
|
3
3
|
/** The zone a date's wall clock is read in. Default `UTC`. */
|
|
4
4
|
timeZone?: string;
|
|
@@ -10,7 +10,8 @@ export declare const XLSX_TYPE = "application/vnd.openxmlformats-officedocument.
|
|
|
10
10
|
/** `A`, `Z`, `AA`: the letters of a column counted from 0. */
|
|
11
11
|
export declare const columnName: (index: number) => string;
|
|
12
12
|
/**
|
|
13
|
-
* The sheets as the bytes of an .xlsx file. One sheet, or several (a tab each)
|
|
14
|
-
*
|
|
13
|
+
* The sheets as the bytes of an .xlsx file. One sheet, or several (a tab each): rows under a header
|
|
14
|
+
* (`Sheet`), or cells laid out one by one (`LaidSheet`). Rows may come page by page (an async
|
|
15
|
+
* iterable); the workbook is still built whole before it is returned.
|
|
15
16
|
*/
|
|
16
|
-
export declare const xlsx: (sheets: Sheet<unknown> | readonly Sheet<unknown>[], options?: XlsxOptions) => Promise<Uint8Array>;
|
|
17
|
+
export declare const xlsx: (sheets: Sheet<unknown> | LaidSheet | readonly (Sheet<unknown> | LaidSheet)[], options?: XlsxOptions) => Promise<Uint8Array>;
|
package/dist/xlsx.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { checkTimeZone, serialDate } from './dates.js';
|
|
2
|
-
import { cellOf, rowsOf } from './sheet.js';
|
|
2
|
+
import { cellOf, rowsOf, } from './sheet.js';
|
|
3
3
|
import { zip } from './zip.js';
|
|
4
4
|
export const XLSX_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
|
5
5
|
const MAX_ROWS = 1_048_576;
|
|
@@ -28,18 +28,111 @@ const textWidth = (text) => {
|
|
|
28
28
|
}
|
|
29
29
|
return width;
|
|
30
30
|
};
|
|
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 THIN = ['left', 'right', 'top', 'bottom']
|
|
40
|
+
.map((side) => `<${side} style="thin"><color auto="1"/></${side}>`)
|
|
41
|
+
.join('');
|
|
31
42
|
class Styles {
|
|
32
43
|
#formats = new Map();
|
|
44
|
+
#looks = new Map();
|
|
45
|
+
#xfs = [];
|
|
46
|
+
#fonts = new Map();
|
|
47
|
+
#fills = new Map();
|
|
48
|
+
#bordered = false;
|
|
33
49
|
of(format) {
|
|
34
|
-
|
|
50
|
+
return this.look({ ...(format === undefined ? {} : { format }) });
|
|
51
|
+
}
|
|
52
|
+
look(look) {
|
|
53
|
+
const format = look.format === '' ? undefined : look.format;
|
|
54
|
+
const flags = [look.bold, look.shade, look.border, look.wrap, look.center]
|
|
55
|
+
.map((on) => (on === true ? '1' : '0'))
|
|
56
|
+
.join('');
|
|
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 ?? '');
|
|
65
|
+
if (key === '00000')
|
|
35
66
|
return 0;
|
|
36
|
-
|
|
67
|
+
if (key === '10000')
|
|
68
|
+
return 1;
|
|
69
|
+
let index = this.#looks.get(key);
|
|
37
70
|
if (index === undefined) {
|
|
38
|
-
index = this.#
|
|
39
|
-
this.#
|
|
71
|
+
index = this.#xfs.length + 2;
|
|
72
|
+
this.#looks.set(key, index);
|
|
73
|
+
this.#xfs.push(this.#xf(look, format));
|
|
40
74
|
}
|
|
41
75
|
return index;
|
|
42
76
|
}
|
|
77
|
+
#numFmt(format) {
|
|
78
|
+
if (format === undefined)
|
|
79
|
+
return 0;
|
|
80
|
+
let at = this.#formats.get(format);
|
|
81
|
+
if (at === undefined) {
|
|
82
|
+
at = this.#formats.size;
|
|
83
|
+
this.#formats.set(format, at);
|
|
84
|
+
}
|
|
85
|
+
return 164 + at;
|
|
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
|
+
}
|
|
114
|
+
#xf(look, format) {
|
|
115
|
+
const on = (flag, text) => (flag === true ? text : '');
|
|
116
|
+
this.#bordered ||= look.border === true;
|
|
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"` +
|
|
124
|
+
on(format !== undefined, ' applyNumberFormat="1"') +
|
|
125
|
+
on(font !== 0, ' applyFont="1"') +
|
|
126
|
+
on(fill !== 0, ' applyFill="1"') +
|
|
127
|
+
on(look.border, ' applyBorder="1"') +
|
|
128
|
+
on(aligned, ' applyAlignment="1"');
|
|
129
|
+
if (!aligned)
|
|
130
|
+
return `<xf ${attrs}/>`;
|
|
131
|
+
const alignment = (across === undefined ? '' : ` horizontal="${across}"`) +
|
|
132
|
+
on(upDown, ` vertical="${on(look.center, 'center') || 'top'}"`) +
|
|
133
|
+
on(look.wrap, ' wrapText="1"');
|
|
134
|
+
return `<xf ${attrs}><alignment${alignment}/></xf>`;
|
|
135
|
+
}
|
|
43
136
|
xml() {
|
|
44
137
|
const formats = [...this.#formats.keys()];
|
|
45
138
|
const numFmts = formats.length
|
|
@@ -47,40 +140,79 @@ class Styles {
|
|
|
47
140
|
.map((code, i) => `<numFmt numFmtId="${String(164 + i)}" formatCode="${escaped(code)}"/>`)
|
|
48
141
|
.join('')}</numFmts>`
|
|
49
142
|
: '';
|
|
50
|
-
const xfs = formats
|
|
51
|
-
.map((_, i) => `<xf numFmtId="${String(164 + i)}" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/>`)
|
|
52
|
-
.join('');
|
|
53
143
|
return (`${XML}<styleSheet xmlns="${MAIN}">${numFmts}` +
|
|
54
|
-
`<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font
|
|
55
|
-
|
|
56
|
-
|
|
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>` +
|
|
154
|
+
`<borders count="${this.#bordered ? '2' : '1'}"><border><left/><right/><top/><bottom/><diagonal/></border>${this.#bordered ? `<border>${THIN}<diagonal/></border>` : ''}</borders>` +
|
|
57
155
|
`<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>` +
|
|
58
|
-
`<cellXfs count="${String(
|
|
59
|
-
`<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>${xfs}</cellXfs>` +
|
|
156
|
+
`<cellXfs count="${String(this.#xfs.length + 2)}"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>` +
|
|
157
|
+
`<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>${this.#xfs.join('')}</cellXfs>` +
|
|
60
158
|
`<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>` +
|
|
61
159
|
`</styleSheet>`);
|
|
62
160
|
}
|
|
63
161
|
}
|
|
64
|
-
const
|
|
65
|
-
if (cell
|
|
66
|
-
|
|
162
|
+
const styleOf = (cell, plan, styles, look) => {
|
|
163
|
+
if (cell instanceof Date) {
|
|
164
|
+
if (Number.isNaN(cell.getTime()))
|
|
165
|
+
return 0;
|
|
166
|
+
return look
|
|
167
|
+
? styles.look({ ...look, format: look.format ?? DATE_FORMAT })
|
|
168
|
+
: plan.numberStyle || styles.of(DATE_FORMAT);
|
|
169
|
+
}
|
|
67
170
|
if (typeof cell === 'number') {
|
|
68
171
|
if (!Number.isFinite(cell))
|
|
69
|
-
return
|
|
70
|
-
|
|
71
|
-
|
|
172
|
+
return 0;
|
|
173
|
+
return look ? styles.look(look) : plan.numberStyle;
|
|
174
|
+
}
|
|
175
|
+
if (!look)
|
|
176
|
+
return 0;
|
|
177
|
+
const { format: _format, ...bare } = look;
|
|
178
|
+
return styles.look(bare);
|
|
179
|
+
};
|
|
180
|
+
const cellXml = (cell, ref, plan, styles, timeZone, look, formula) => {
|
|
181
|
+
const index = styleOf(cell, plan, styles, look);
|
|
182
|
+
const s = index ? ` s="${String(index)}"` : '';
|
|
183
|
+
if (formula !== undefined)
|
|
184
|
+
return formulaXml(formula, cell, ref, s, timeZone);
|
|
185
|
+
if (cell === null || cell === undefined || cell === '')
|
|
186
|
+
return s ? `<c r="${ref}"${s}/>` : '';
|
|
187
|
+
if (typeof cell === 'number') {
|
|
188
|
+
return Number.isFinite(cell) ? `<c r="${ref}"${s}><v>${String(cell)}</v></c>` : '';
|
|
72
189
|
}
|
|
73
190
|
if (typeof cell === 'boolean')
|
|
74
|
-
return `<c r="${ref}" t="b"><v>${cell ? '1' : '0'}</v></c>`;
|
|
191
|
+
return `<c r="${ref}"${s} t="b"><v>${cell ? '1' : '0'}</v></c>`;
|
|
75
192
|
if (cell instanceof Date) {
|
|
76
193
|
if (Number.isNaN(cell.getTime()))
|
|
77
194
|
return '';
|
|
78
|
-
|
|
79
|
-
return `<c r="${ref}" s="${String(style)}"><v>${String(serialDate(cell, timeZone))}</v></c>`;
|
|
195
|
+
return `<c r="${ref}"${s}><v>${String(serialDate(cell, timeZone))}</v></c>`;
|
|
80
196
|
}
|
|
81
197
|
if (cell.length > MAX_TEXT)
|
|
82
198
|
throw new RangeError(`cell ${ref} holds ${String(cell.length)} characters; a workbook cell holds at most ${String(MAX_TEXT)}`);
|
|
83
|
-
return `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${escaped(cell)}</t></is></c>`;
|
|
199
|
+
return `<c r="${ref}"${s} t="inlineStr"><is><t xml:space="preserve">${escaped(cell)}</t></is></c>`;
|
|
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>`;
|
|
84
216
|
};
|
|
85
217
|
const MEASURED_ROWS = 200;
|
|
86
218
|
const shownWidth = (cell) => {
|
|
@@ -141,6 +273,51 @@ const sheetXml = async (sheet, styles, timeZone) => {
|
|
|
141
273
|
(columns.length ? `<autoFilter ref="A1:${last}"/>` : '') +
|
|
142
274
|
`</worksheet>`);
|
|
143
275
|
};
|
|
276
|
+
const isLooked = (cell) => typeof cell === 'object' && cell !== null && !(cell instanceof Date);
|
|
277
|
+
const span = (n) => Math.max(1, Math.trunc(n ?? 1));
|
|
278
|
+
const laidXml = (sheet, styles, timeZone) => {
|
|
279
|
+
if (sheet.cells.length > MAX_ROWS)
|
|
280
|
+
throw new RangeError(`a sheet has at most ${String(MAX_ROWS)} rows`);
|
|
281
|
+
const merges = (sheet.merges ?? []).filter((m) => span(m.rows) > 1 || span(m.columns) > 1);
|
|
282
|
+
const across = new Set(merges.filter((m) => span(m.columns) > 1).map((m) => `${String(m.row)}:${String(m.column)}`));
|
|
283
|
+
const measured = [];
|
|
284
|
+
const rows = sheet.cells.map((row, r) => {
|
|
285
|
+
if (row.length > MAX_COLUMNS)
|
|
286
|
+
throw new RangeError(`a sheet has at most ${String(MAX_COLUMNS)} columns`);
|
|
287
|
+
const cells = row.map((cell, c) => {
|
|
288
|
+
const { value, formula, ...look } = isLooked(cell)
|
|
289
|
+
? cell
|
|
290
|
+
: { value: cell, formula: undefined };
|
|
291
|
+
if (!across.has(`${String(r)}:${String(c)}`))
|
|
292
|
+
measured[c] = Math.max(measured[c] ?? 0, shownWidth(value));
|
|
293
|
+
return cellXml(value, `${columnName(c)}${String(r + 1)}`, { numberStyle: 0 }, styles, timeZone, look, formula);
|
|
294
|
+
});
|
|
295
|
+
return `<row r="${String(r + 1)}">${cells.join('')}</row>`;
|
|
296
|
+
});
|
|
297
|
+
const cols = Array.from(measured, (width, i) => {
|
|
298
|
+
const n = String(i + 1);
|
|
299
|
+
const shown = sheet.widths?.[i] ?? Math.min(60, Math.max(8, width + 2));
|
|
300
|
+
return `<col min="${n}" max="${n}" width="${String(shown)}" customWidth="1"/>`;
|
|
301
|
+
}).join('');
|
|
302
|
+
const frozen = Math.max(0, Math.trunc(sheet.frozen ?? 0));
|
|
303
|
+
const pane = frozen
|
|
304
|
+
? `<pane ySplit="${String(frozen)}" topLeftCell="A${String(frozen + 1)}" activePane="bottomLeft" state="frozen"/>`
|
|
305
|
+
: '';
|
|
306
|
+
const merged = merges
|
|
307
|
+
.map((m) => {
|
|
308
|
+
const from = `${columnName(m.column)}${String(m.row + 1)}`;
|
|
309
|
+
const to = `${columnName(m.column + span(m.columns) - 1)}${String(m.row + span(m.rows))}`;
|
|
310
|
+
return `<mergeCell ref="${from}:${to}"/>`;
|
|
311
|
+
})
|
|
312
|
+
.join('');
|
|
313
|
+
return (`${XML}<worksheet xmlns="${MAIN}">` +
|
|
314
|
+
`<sheetViews><sheetView workbookViewId="0">${pane}</sheetView></sheetViews>` +
|
|
315
|
+
`<sheetFormatPr defaultRowHeight="15"/>` +
|
|
316
|
+
(cols ? `<cols>${cols}</cols>` : '') +
|
|
317
|
+
`<sheetData>${rows.join('')}</sheetData>` +
|
|
318
|
+
(merged ? `<mergeCells count="${String(merges.length)}">${merged}</mergeCells>` : '') +
|
|
319
|
+
`</worksheet>`);
|
|
320
|
+
};
|
|
144
321
|
const sheetNames = (sheets) => {
|
|
145
322
|
const taken = new Set();
|
|
146
323
|
return sheets.map((sheet, i) => {
|
|
@@ -178,8 +355,9 @@ export const xlsx = async (sheets, options = {}) => {
|
|
|
178
355
|
const styles = new Styles();
|
|
179
356
|
const names = sheetNames(list);
|
|
180
357
|
const parts = [];
|
|
181
|
-
for (const sheet of list)
|
|
182
|
-
parts.push(await sheetXml(sheet, styles, timeZone));
|
|
358
|
+
for (const sheet of list) {
|
|
359
|
+
parts.push('cells' in sheet ? laidXml(sheet, styles, timeZone) : await sheetXml(sheet, styles, timeZone));
|
|
360
|
+
}
|
|
183
361
|
const ids = list.map((_, i) => String(i + 1));
|
|
184
362
|
const encoder = new TextEncoder();
|
|
185
363
|
const file = (path, text) => ({ path, data: encoder.encode(text) });
|
|
@@ -198,7 +376,9 @@ export const xlsx = async (sheets, options = {}) => {
|
|
|
198
376
|
ids
|
|
199
377
|
.map((id, i) => `<sheet name="${escaped(names[i] ?? '')}" sheetId="${id}" r:id="rId${id}"/>`)
|
|
200
378
|
.join('') +
|
|
201
|
-
`</sheets
|
|
379
|
+
`</sheets>` +
|
|
380
|
+
(parts.some((part) => part.includes('<f>')) ? `<calcPr fullCalcOnLoad="1"/>` : '') +
|
|
381
|
+
`</workbook>`),
|
|
202
382
|
file('xl/_rels/workbook.xml.rels', `${XML}<Relationships xmlns="${PKG}/relationships">` +
|
|
203
383
|
ids
|
|
204
384
|
.map((id) => `<Relationship Id="rId${id}" Type="${REL}/worksheet" Target="worksheets/sheet${id}.xml"/>`)
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@20baht/export",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20.19.0"
|
|
7
7
|
},
|
|
8
|
-
"description": "Rows as a CSV or an .xlsx file, on a server or in a browser: Thai that opens in Excel, no formula a cell can smuggle in, dates and number formats, a table's columns as the header. No dependencies.",
|
|
8
|
+
"description": "Rows as a CSV or an .xlsx file, on a server or in a browser: Thai that opens in Excel, no formula a cell can smuggle in, dates and number formats, a table's columns as the header, and a sheet laid out cell by cell (merged cells, borders) for a document. No dependencies.",
|
|
9
9
|
"license": "MIT",
|
|
10
10
|
"author": "Nattapong Promthong",
|
|
11
11
|
"repository": {
|