javascript-excel 2.0.0-alpha.2 → 2.0.0-alpha.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 +151 -21
- package/dist/address-DUn7-5OS.js +75 -0
- package/dist/address-DZBHchLv.cjs +122 -0
- package/dist/{auto-width-2oBzjeNG.d.cts → auto-width-DRHsPKNk.d.cts} +1 -1
- package/dist/cells-CPXU722t.cjs +33 -0
- package/dist/cells-CrMF8h_t.js +28 -0
- package/dist/colors-B8Nf_xTx.js +114 -0
- package/dist/colors-oBpjx97l.cjs +119 -0
- package/dist/csv.d.cts +4 -1
- package/dist/csv.d.ts +4 -1
- package/dist/dataset-KeMzHCGl.js +664 -0
- package/dist/dataset-UUZCzsi3.cjs +687 -0
- package/dist/dates-BXcSWf9_.js +64 -0
- package/dist/dates-CA1dCizp.cjs +75 -0
- package/dist/dom.cjs +5 -2
- package/dist/dom.d.cts +5 -2
- package/dist/dom.d.ts +4 -1
- package/dist/dom.js +4 -1
- package/dist/{numfmt-Dv6AjopS.cjs → dos-time-FZ7-1tot.cjs} +0 -199
- package/dist/{numfmt-BBgB7iQA.js → dos-time-dD0z1YWU.js} +2 -177
- package/dist/format.cjs +1264 -0
- package/dist/format.d.cts +59 -0
- package/dist/format.d.ts +59 -0
- package/dist/format.js +1262 -0
- package/dist/import.cjs +10 -0
- package/dist/import.d.cts +10 -0
- package/dist/import.d.ts +10 -0
- package/dist/import.js +1 -0
- package/dist/index.cjs +24 -607
- package/dist/index.d.cts +32 -6
- package/dist/index.d.ts +31 -5
- package/dist/index.js +10 -594
- package/dist/{warnings-C_12PT4t.d.cts → model-0JikLfuM.d.cts} +1 -41
- package/dist/{warnings-DXJKe1lx.d.ts → model-0JikLfuM.d.ts} +1 -41
- package/dist/numfmt-BmEbm78Y.cjs +125 -0
- package/dist/numfmt-DCDrX9P1.js +114 -0
- package/dist/pipeline-BAJtzBdW.js +1085 -0
- package/dist/pipeline-Bnf7EU3X.cjs +1132 -0
- package/dist/pipeline-CctEa86r.d.cts +186 -0
- package/dist/pipeline-I8SLmV9S.d.ts +186 -0
- package/dist/{read-Ym1voUct.cjs → read-CZEWV4rK.cjs} +181 -17
- package/dist/{read-DDN5ZsPe.js → read-LWti17lz.js} +169 -5
- package/dist/read.cjs +1 -1
- package/dist/read.d.cts +78 -4
- package/dist/read.d.ts +78 -4
- package/dist/read.js +1 -1
- package/dist/render.cjs +751 -0
- package/dist/render.d.cts +215 -0
- package/dist/render.d.ts +215 -0
- package/dist/render.js +732 -0
- package/dist/{sheet-names-uT2EH5Ui.js → sheet-names-7p-joVsG.js} +2 -101
- package/dist/{sheet-names-qpXsvMpM.cjs → sheet-names-B8U5RAW0.cjs} +14 -167
- package/dist/warnings-B1v58nCZ.d.cts +41 -0
- package/dist/warnings-B1v58nCZ.d.ts +41 -0
- package/dist/worker.cjs +10 -2
- package/dist/worker.d.cts +10 -4
- package/dist/worker.d.ts +10 -4
- package/dist/worker.js +10 -2
- package/dist/{write-CYpLGuzl.d.ts → write-DM6ieuQY.d.ts} +2 -1
- package/dist/{write-DubvcG-x.js → write-DjgWy1PK.js} +5 -2
- package/dist/{write-C5JgeIar.d.cts → write-DtjfdIFm.d.cts} +2 -1
- package/dist/{write-BOh9jfu1.cjs → write-f9kcYf5K.cjs} +31 -28
- package/package.json +32 -1
- package/dist/read-C6L7Nyy3.d.cts +0 -78
- package/dist/read-Ddkks7qC.d.ts +0 -78
|
@@ -0,0 +1,664 @@
|
|
|
1
|
+
import { a as decodeRange, c as encodeRange, o as encodeCell, r as decodeCell, s as encodeCol, t as MAX_COLS } from "./address-DUn7-5OS.js";
|
|
2
|
+
import { t as cellText } from "./cells-CrMF8h_t.js";
|
|
3
|
+
import { t as dateToSerial } from "./dates-BXcSWf9_.js";
|
|
4
|
+
import { o as ValidationError } from "./errors-CvGlfw0E.js";
|
|
5
|
+
import { n as parseIsoDate, t as isoDate } from "./iso-date-CXnn-9mT.js";
|
|
6
|
+
import { l as textWidth, m as mergeStyles, n as validateSheetName, r as AUTO_WIDTH } from "./sheet-names-7p-joVsG.js";
|
|
7
|
+
// src/dataset.ts
|
|
8
|
+
/**
|
|
9
|
+
* Dataset builders (docs/api.md §4.3): `{ columns, data }` ↔ Sheet.
|
|
10
|
+
*
|
|
11
|
+
* `fromDataset` lays out header rows (with header groups as merged cells),
|
|
12
|
+
* data rows and an optional totals row; `fromDatasets` stacks several blocks
|
|
13
|
+
* on one sheet; `toDataset` goes the other way for import.
|
|
14
|
+
*/
|
|
15
|
+
function columnError(message, details = {}) {
|
|
16
|
+
return new ValidationError("INVALID_COLUMN", message, { details });
|
|
17
|
+
}
|
|
18
|
+
const FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set([
|
|
19
|
+
"__proto__",
|
|
20
|
+
"prototype",
|
|
21
|
+
"constructor"
|
|
22
|
+
]);
|
|
23
|
+
/** Parses 'a.b', 'items[0].name', "a['x.y']" and 'a["x"]' into segments. */
|
|
24
|
+
function parsePath(path) {
|
|
25
|
+
const segs = [];
|
|
26
|
+
let i = 0;
|
|
27
|
+
const fail = () => {
|
|
28
|
+
throw columnError(`Invalid path ${JSON.stringify(path)}.`, { path });
|
|
29
|
+
};
|
|
30
|
+
if (typeof path !== "string" || path.length === 0) fail();
|
|
31
|
+
while (i < path.length) {
|
|
32
|
+
if (path[i] === "[") {
|
|
33
|
+
const q = path[i + 1];
|
|
34
|
+
if (q === "'" || q === "\"") {
|
|
35
|
+
const end = path.indexOf(`${q}]`, i + 2);
|
|
36
|
+
if (end < 0) fail();
|
|
37
|
+
segs.push(path.slice(i + 2, end));
|
|
38
|
+
i = end + 2;
|
|
39
|
+
} else {
|
|
40
|
+
const end = path.indexOf("]", i);
|
|
41
|
+
const n = path.slice(i + 1, end);
|
|
42
|
+
if (end < 0 || !/^\d+$/.test(n)) fail();
|
|
43
|
+
segs.push(n);
|
|
44
|
+
i = end + 1;
|
|
45
|
+
}
|
|
46
|
+
if (path[i] === ".") i++;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
let j = i;
|
|
50
|
+
while (j < path.length && path[j] !== "." && path[j] !== "[") j++;
|
|
51
|
+
if (j === i) fail();
|
|
52
|
+
segs.push(path.slice(i, j));
|
|
53
|
+
i = path[j] === "." ? j + 1 : j;
|
|
54
|
+
if (path[j] === "." && i >= path.length) fail();
|
|
55
|
+
}
|
|
56
|
+
for (const s of segs) if (FORBIDDEN_SEGMENTS.has(s)) throw columnError(`Path ${JSON.stringify(path)} uses the forbidden segment ${s}.`, {
|
|
57
|
+
path,
|
|
58
|
+
segment: s
|
|
59
|
+
});
|
|
60
|
+
return segs;
|
|
61
|
+
}
|
|
62
|
+
const own = (o, k) => o !== null && (typeof o === "object" || typeof o === "function") && Object.prototype.hasOwnProperty.call(o, k) ? o[k] : void 0;
|
|
63
|
+
function accessorOf(def, position) {
|
|
64
|
+
if ([
|
|
65
|
+
def.key !== void 0,
|
|
66
|
+
def.path !== void 0,
|
|
67
|
+
def.value !== void 0,
|
|
68
|
+
def.index !== void 0
|
|
69
|
+
].filter(Boolean).length > 1) throw columnError(`Column ${JSON.stringify(def.title ?? def.key ?? def.path)} has more than one accessor (key, path, value, index).`);
|
|
70
|
+
if (def.key !== void 0) {
|
|
71
|
+
if (typeof def.key !== "string") throw columnError("key must be a string.");
|
|
72
|
+
const key = def.key;
|
|
73
|
+
return (row) => own(row, key);
|
|
74
|
+
}
|
|
75
|
+
if (def.path !== void 0) {
|
|
76
|
+
const segs = parsePath(def.path);
|
|
77
|
+
return (row) => {
|
|
78
|
+
let v = row;
|
|
79
|
+
for (const s of segs) {
|
|
80
|
+
v = own(v, s);
|
|
81
|
+
if (v === void 0) return void 0;
|
|
82
|
+
}
|
|
83
|
+
return v;
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (def.value !== void 0) {
|
|
87
|
+
if (typeof def.value !== "function") throw columnError("value must be a function.");
|
|
88
|
+
const fn = def.value;
|
|
89
|
+
return (row, rowIndex) => fn(row, { rowIndex });
|
|
90
|
+
}
|
|
91
|
+
const index = def.index ?? position;
|
|
92
|
+
if (!Number.isInteger(index) || index < 0) throw columnError(`index must be a non-negative integer, got ${String(def.index)}.`);
|
|
93
|
+
const named = def.index !== void 0;
|
|
94
|
+
return (row) => {
|
|
95
|
+
if (Array.isArray(row)) return row[index];
|
|
96
|
+
if (named || row === null || row === void 0) return void 0;
|
|
97
|
+
throw columnError(`Column ${JSON.stringify(def.title ?? `#${position + 1}`)} has no accessor (key, path, value or index) and the data rows are objects.`);
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
const PLAIN_NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
|
|
101
|
+
function isCellObject(v) {
|
|
102
|
+
return typeof v === "object" && v !== null && !(v instanceof Date) && !("error" in v) && !("richText" in v);
|
|
103
|
+
}
|
|
104
|
+
function coerce(v, type) {
|
|
105
|
+
if (v === null || v === void 0 || type === void 0 || type === "auto") return {
|
|
106
|
+
value: v,
|
|
107
|
+
failed: false
|
|
108
|
+
};
|
|
109
|
+
switch (type) {
|
|
110
|
+
case "string":
|
|
111
|
+
if (v instanceof Date) return {
|
|
112
|
+
value: Number.isFinite(v.getTime()) ? isoDate(v, "local") : "",
|
|
113
|
+
failed: false
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
value: typeof v === "object" ? cellText(v) : String(v),
|
|
117
|
+
failed: false
|
|
118
|
+
};
|
|
119
|
+
case "number":
|
|
120
|
+
if (typeof v === "number") return {
|
|
121
|
+
value: v,
|
|
122
|
+
failed: false
|
|
123
|
+
};
|
|
124
|
+
if (typeof v === "string" && PLAIN_NUMBER.test(v.trim())) return {
|
|
125
|
+
value: Number(v.trim()),
|
|
126
|
+
failed: false
|
|
127
|
+
};
|
|
128
|
+
return {
|
|
129
|
+
value: typeof v === "object" && !(v instanceof Date) ? cellText(v) : String(v instanceof Date ? isoDate(v, "local") : v),
|
|
130
|
+
failed: true
|
|
131
|
+
};
|
|
132
|
+
case "boolean":
|
|
133
|
+
if (typeof v === "boolean") return {
|
|
134
|
+
value: v,
|
|
135
|
+
failed: false
|
|
136
|
+
};
|
|
137
|
+
if (typeof v === "string" && /^(true|false)$/i.test(v.trim())) return {
|
|
138
|
+
value: v.trim().toLowerCase() === "true",
|
|
139
|
+
failed: false
|
|
140
|
+
};
|
|
141
|
+
return {
|
|
142
|
+
value: typeof v === "object" ? cellText(v) : String(v),
|
|
143
|
+
failed: true
|
|
144
|
+
};
|
|
145
|
+
case "date":
|
|
146
|
+
case "datetime":
|
|
147
|
+
if (v instanceof Date) return Number.isFinite(v.getTime()) ? {
|
|
148
|
+
value: v,
|
|
149
|
+
failed: false
|
|
150
|
+
} : {
|
|
151
|
+
value: "Invalid Date",
|
|
152
|
+
failed: true
|
|
153
|
+
};
|
|
154
|
+
if (typeof v === "number" && Number.isFinite(v)) return {
|
|
155
|
+
value: new Date(v),
|
|
156
|
+
failed: false
|
|
157
|
+
};
|
|
158
|
+
if (typeof v === "string") {
|
|
159
|
+
const d = parseIsoDate(v);
|
|
160
|
+
if (d) return {
|
|
161
|
+
value: d,
|
|
162
|
+
failed: false
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
value: typeof v === "object" ? cellText(v) : String(v),
|
|
167
|
+
failed: true
|
|
168
|
+
};
|
|
169
|
+
default: throw columnError(`Unknown column type ${JSON.stringify(type)}.`, { type });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const set = (g, r, c, v) => {
|
|
173
|
+
if (r >= 1048576 || c >= 16384) throw new ValidationError("OUT_OF_BOUNDS", `Dataset does not fit the sheet: ${encodeCol(Math.min(c, MAX_COLS - 1))}${r + 1} is out of bounds.`);
|
|
174
|
+
(g.rows[r] ??= [])[c] = v;
|
|
175
|
+
};
|
|
176
|
+
const range = (r1, c1, r2, c2) => {
|
|
177
|
+
const a = encodeCell({
|
|
178
|
+
row: r1,
|
|
179
|
+
col: c1
|
|
180
|
+
});
|
|
181
|
+
const b = encodeCell({
|
|
182
|
+
row: r2,
|
|
183
|
+
col: c2
|
|
184
|
+
});
|
|
185
|
+
return a === b ? a : `${a}:${b}`;
|
|
186
|
+
};
|
|
187
|
+
function normalise(defs) {
|
|
188
|
+
const out = [];
|
|
189
|
+
for (const d of defs) {
|
|
190
|
+
if (!d) continue;
|
|
191
|
+
if (typeof d !== "object") throw columnError("A column definition must be an object.");
|
|
192
|
+
if ("children" in d && d.children !== void 0) {
|
|
193
|
+
if (!Array.isArray(d.children)) throw columnError("children must be an array.");
|
|
194
|
+
const children = normalise(d.children);
|
|
195
|
+
if (children.length) out.push({
|
|
196
|
+
group: d,
|
|
197
|
+
children
|
|
198
|
+
});
|
|
199
|
+
} else out.push({ leaf: d });
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
const depthOf = (n) => "group" in n ? 1 + Math.max(...n.children.map(depthOf)) : 1;
|
|
204
|
+
const leafCount = (n) => "group" in n ? n.children.reduce((s, c) => s + leafCount(c), 0) : 1;
|
|
205
|
+
function titleCell(title, style) {
|
|
206
|
+
if (title === void 0) return style ? {
|
|
207
|
+
value: "",
|
|
208
|
+
style
|
|
209
|
+
} : "";
|
|
210
|
+
if (isCellObject(title)) return {
|
|
211
|
+
...title,
|
|
212
|
+
style: mergeStyles(style, title.style)
|
|
213
|
+
};
|
|
214
|
+
return style ? {
|
|
215
|
+
value: title,
|
|
216
|
+
style
|
|
217
|
+
} : title;
|
|
218
|
+
}
|
|
219
|
+
function layoutBlock(g, dataset, options, top, left, sheet) {
|
|
220
|
+
if (typeof dataset !== "object" || dataset === null || !Array.isArray(dataset.data)) throw columnError("A dataset needs a data array.");
|
|
221
|
+
const data = dataset.data;
|
|
222
|
+
let defs = dataset.columns;
|
|
223
|
+
let inferredArrays = false;
|
|
224
|
+
if (defs === void 0) {
|
|
225
|
+
const first = data.find((r) => r !== null && r !== void 0);
|
|
226
|
+
if (Array.isArray(first)) {
|
|
227
|
+
inferredArrays = true;
|
|
228
|
+
const width = data.reduce((m, r) => Array.isArray(r) ? Math.max(m, r.length) : m, 0);
|
|
229
|
+
defs = Array.from({ length: width }, (_, i) => ({ index: i }));
|
|
230
|
+
} else if (first !== void 0 && typeof first === "object") defs = Object.keys(first).map((key) => ({
|
|
231
|
+
title: key,
|
|
232
|
+
key
|
|
233
|
+
}));
|
|
234
|
+
else defs = [];
|
|
235
|
+
}
|
|
236
|
+
if (!Array.isArray(defs)) throw columnError("columns must be an array.");
|
|
237
|
+
const nodes = normalise(defs);
|
|
238
|
+
const leaves = [];
|
|
239
|
+
const collect = (n) => {
|
|
240
|
+
if ("group" in n) n.children.forEach(collect);
|
|
241
|
+
else {
|
|
242
|
+
const def = n.leaf;
|
|
243
|
+
leaves.push({
|
|
244
|
+
def,
|
|
245
|
+
col: leaves.length,
|
|
246
|
+
get: accessorOf(def, leaves.length)
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
nodes.forEach(collect);
|
|
251
|
+
const headerOn = options.header !== false && !inferredArrays && leaves.length > 0;
|
|
252
|
+
const headerRows = headerOn ? Math.max(...nodes.map(depthOf)) : 0;
|
|
253
|
+
const baseHeader = options.headerStyle ?? { font: { bold: true } };
|
|
254
|
+
for (const { def, col } of leaves) {
|
|
255
|
+
const c = left + col;
|
|
256
|
+
if (def.width === "auto" || def.width === void 0 && options.autoWidth) g.autoCols.add(c);
|
|
257
|
+
else if (def.width !== void 0 && !g.widths.has(c)) g.widths.set(c, def.width);
|
|
258
|
+
if (def.hidden) g.hidden.add(c);
|
|
259
|
+
}
|
|
260
|
+
if (headerOn) {
|
|
261
|
+
let next = 0;
|
|
262
|
+
const place = (n, level) => {
|
|
263
|
+
if ("group" in n) {
|
|
264
|
+
const span = leafCount(n);
|
|
265
|
+
const c = left + next;
|
|
266
|
+
set(g, top + level, c, titleCell(n.group.title, mergeStyles(baseHeader, n.group.headerStyle)));
|
|
267
|
+
if (span > 1) g.merges.push(range(top + level, c, top + level, c + span - 1));
|
|
268
|
+
n.children.forEach((child) => place(child, level + 1));
|
|
269
|
+
} else {
|
|
270
|
+
const def = n.leaf;
|
|
271
|
+
const c = left + next++;
|
|
272
|
+
const cell = titleCell(def.title ?? def.key ?? def.path ?? "", mergeStyles(baseHeader, def.headerStyle));
|
|
273
|
+
set(g, top + level, c, cell);
|
|
274
|
+
if (level < headerRows - 1) g.merges.push(range(top + level, c, top + headerRows - 1, c));
|
|
275
|
+
if (g.autoCols.has(c)) g.measured.set(c, Math.max(g.measured.get(c) ?? 0, textWidth(cellText(cell))));
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
nodes.forEach((n) => place(n, 0));
|
|
279
|
+
}
|
|
280
|
+
const warn = options.onWarning ?? (() => {});
|
|
281
|
+
const dataTop = top + headerRows;
|
|
282
|
+
const sampleRows = typeof options.autoWidth === "object" && options.autoWidth.sampleRows !== void 0 ? options.autoWidth.sampleRows : 1e400;
|
|
283
|
+
const columnValues = leaves.map(() => []);
|
|
284
|
+
const columnStyles = leaves.map(({ def }) => {
|
|
285
|
+
const typeFmt = def.type === "date" ? { numFmt: 14 } : def.type === "datetime" ? { numFmt: 22 } : void 0;
|
|
286
|
+
const merged = mergeStyles(typeFmt, def.style, def.numFmt !== void 0 ? { numFmt: def.numFmt } : void 0);
|
|
287
|
+
return Object.keys(merged).length ? merged : void 0;
|
|
288
|
+
});
|
|
289
|
+
const rowMerges = /* @__PURE__ */ new WeakMap();
|
|
290
|
+
const styleFor = (col, rowStyle, cellStyle) => {
|
|
291
|
+
if (cellStyle) return mergeStyles(columnStyles[col], rowStyle, cellStyle);
|
|
292
|
+
if (!rowStyle) return columnStyles[col];
|
|
293
|
+
let perColumn = rowMerges.get(rowStyle);
|
|
294
|
+
if (!perColumn) rowMerges.set(rowStyle, perColumn = []);
|
|
295
|
+
if (!(col in perColumn)) perColumn[col] = mergeStyles(columnStyles[col], rowStyle);
|
|
296
|
+
return perColumn[col];
|
|
297
|
+
};
|
|
298
|
+
data.forEach((row, i) => {
|
|
299
|
+
const r = dataTop + i;
|
|
300
|
+
const rowStyle = options.rowStyle?.(row, i);
|
|
301
|
+
for (const { def, col, get } of leaves) {
|
|
302
|
+
const c = left + col;
|
|
303
|
+
const refOf = () => encodeCell({
|
|
304
|
+
row: r,
|
|
305
|
+
col: c
|
|
306
|
+
});
|
|
307
|
+
const raw = get(row, i);
|
|
308
|
+
let cell = isCellObject(raw) ? { ...raw } : { value: raw };
|
|
309
|
+
if (!cell.formula) {
|
|
310
|
+
const { value, failed } = coerce(cell.value, def.type);
|
|
311
|
+
if (failed) {
|
|
312
|
+
const ref = refOf();
|
|
313
|
+
warn({
|
|
314
|
+
code: "COERCION_FAILED",
|
|
315
|
+
message: `${sheet}!${ref}: value does not fit type '${def.type}'; written as text.`,
|
|
316
|
+
sheet,
|
|
317
|
+
ref
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
cell.value = value;
|
|
321
|
+
}
|
|
322
|
+
if (typeof cell.value === "number" && !Number.isFinite(cell.value)) {
|
|
323
|
+
const ref = refOf();
|
|
324
|
+
warn({
|
|
325
|
+
code: "NON_FINITE_NUMBER",
|
|
326
|
+
message: `${sheet}!${ref}: ${String(cell.value)} cannot be stored; the cell is left empty.`,
|
|
327
|
+
sheet,
|
|
328
|
+
ref
|
|
329
|
+
});
|
|
330
|
+
cell = {
|
|
331
|
+
...cell,
|
|
332
|
+
value: null
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
const style = styleFor(col, rowStyle, isCellObject(raw) ? raw.style : void 0);
|
|
336
|
+
const out = style !== void 0 && Object.keys(style).length > 0 ? {
|
|
337
|
+
...cell,
|
|
338
|
+
style
|
|
339
|
+
} : Object.keys(cell).length === 1 && "value" in cell ? cell.value : cell;
|
|
340
|
+
if (out !== void 0 && out !== null) set(g, r, c, out);
|
|
341
|
+
const v = cell.value;
|
|
342
|
+
if (v !== null && v !== void 0) columnValues[col].push(v);
|
|
343
|
+
if (i < sampleRows && g.autoCols.has(c)) g.measured.set(c, Math.max(g.measured.get(c) ?? 0, textWidth(cellText(out))));
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
const lastDataRow = dataTop + data.length - 1;
|
|
347
|
+
const hasTotals = leaves.some(({ def }) => def.total !== void 0);
|
|
348
|
+
let lastRow = Math.max(top + headerRows - 1, lastDataRow);
|
|
349
|
+
if (hasTotals) {
|
|
350
|
+
const r = lastDataRow + 1;
|
|
351
|
+
const totalsStyle = options.totals?.style;
|
|
352
|
+
leaves.forEach(({ def, col }, k) => {
|
|
353
|
+
const c = left + col;
|
|
354
|
+
const values = columnValues[col];
|
|
355
|
+
const dataRange = data.length ? range(dataTop, c, lastDataRow, c) : "";
|
|
356
|
+
let cell;
|
|
357
|
+
if (def.total === void 0) {
|
|
358
|
+
if (k !== 0 || options.totals?.label === void 0) return;
|
|
359
|
+
cell = {
|
|
360
|
+
value: options.totals.label,
|
|
361
|
+
...totalsStyle ? { style: totalsStyle } : {}
|
|
362
|
+
};
|
|
363
|
+
} else {
|
|
364
|
+
cell = totalCell(def.total, dataRange, values);
|
|
365
|
+
const base = def.total === "count" ? {
|
|
366
|
+
...columnStyles[col],
|
|
367
|
+
numFmt: void 0
|
|
368
|
+
} : columnStyles[col];
|
|
369
|
+
const cellStyle = isCellObject(cell) ? cell.style : void 0;
|
|
370
|
+
const style = mergeStyles(base, totalsStyle, cellStyle);
|
|
371
|
+
if (Object.keys(style).length) cell = isCellObject(cell) ? {
|
|
372
|
+
...cell,
|
|
373
|
+
style
|
|
374
|
+
} : {
|
|
375
|
+
value: cell,
|
|
376
|
+
style
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
set(g, r, c, cell);
|
|
380
|
+
if (g.autoCols.has(c)) g.measured.set(c, Math.max(g.measured.get(c) ?? 0, textWidth(cellText(cell))));
|
|
381
|
+
});
|
|
382
|
+
lastRow = r;
|
|
383
|
+
}
|
|
384
|
+
return {
|
|
385
|
+
headerRows,
|
|
386
|
+
firstRow: top,
|
|
387
|
+
lastHeaderRow: top + headerRows - 1,
|
|
388
|
+
lastDataRow: Math.max(lastDataRow, top + headerRows - 1),
|
|
389
|
+
firstCol: left,
|
|
390
|
+
lastCol: left + Math.max(leaves.length, 1) - 1,
|
|
391
|
+
lastRow
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
const SUBTOTAL = {
|
|
395
|
+
sum: 109,
|
|
396
|
+
average: 101,
|
|
397
|
+
count: 103,
|
|
398
|
+
min: 105,
|
|
399
|
+
max: 104
|
|
400
|
+
};
|
|
401
|
+
function numeric(values) {
|
|
402
|
+
const out = [];
|
|
403
|
+
for (const v of values) if (typeof v === "number") out.push(v);
|
|
404
|
+
else if (v instanceof Date) try {
|
|
405
|
+
out.push(dateToSerial(v));
|
|
406
|
+
} catch {}
|
|
407
|
+
return out;
|
|
408
|
+
}
|
|
409
|
+
function totalCell(total, dataRange, values) {
|
|
410
|
+
if (typeof total === "function") return total({
|
|
411
|
+
range: dataRange,
|
|
412
|
+
values
|
|
413
|
+
});
|
|
414
|
+
if (typeof total === "string" && total in SUBTOTAL) {
|
|
415
|
+
const nums = numeric(values);
|
|
416
|
+
let cached;
|
|
417
|
+
switch (total) {
|
|
418
|
+
case "sum":
|
|
419
|
+
cached = nums.reduce((a, b) => a + b, 0);
|
|
420
|
+
break;
|
|
421
|
+
case "average":
|
|
422
|
+
cached = nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : { error: "#DIV/0!" };
|
|
423
|
+
break;
|
|
424
|
+
case "count":
|
|
425
|
+
cached = values.length;
|
|
426
|
+
break;
|
|
427
|
+
case "min":
|
|
428
|
+
cached = nums.length ? Math.min(...nums) : 0;
|
|
429
|
+
break;
|
|
430
|
+
default: cached = nums.length ? Math.max(...nums) : 0;
|
|
431
|
+
}
|
|
432
|
+
return dataRange ? {
|
|
433
|
+
formula: `SUBTOTAL(${SUBTOTAL[total]},${dataRange})`,
|
|
434
|
+
value: cached
|
|
435
|
+
} : { value: cached };
|
|
436
|
+
}
|
|
437
|
+
return total;
|
|
438
|
+
}
|
|
439
|
+
function finish(g, options, first, name) {
|
|
440
|
+
const sheet = {
|
|
441
|
+
name,
|
|
442
|
+
rows: g.rows
|
|
443
|
+
};
|
|
444
|
+
if (g.merges.length) sheet.merges = g.merges;
|
|
445
|
+
const auto = typeof options.autoWidth === "object" ? options.autoWidth : {};
|
|
446
|
+
const min = auto.min ?? AUTO_WIDTH.min;
|
|
447
|
+
const max = Math.min(255, auto.max ?? AUTO_WIDTH.max);
|
|
448
|
+
const cols = /* @__PURE__ */ new Set([
|
|
449
|
+
...g.widths.keys(),
|
|
450
|
+
...g.autoCols,
|
|
451
|
+
...g.hidden
|
|
452
|
+
]);
|
|
453
|
+
if (cols.size) {
|
|
454
|
+
const colProps = [];
|
|
455
|
+
for (const c of [...cols].sort((a, b) => a - b)) {
|
|
456
|
+
const p = {};
|
|
457
|
+
const w = g.autoCols.has(c) ? Math.min(max, Math.max(min, (g.measured.get(c) ?? 0) + AUTO_WIDTH.padding)) : g.widths.get(c);
|
|
458
|
+
if (w !== void 0) p.width = w;
|
|
459
|
+
if (g.hidden.has(c)) p.hidden = true;
|
|
460
|
+
colProps[c] = p;
|
|
461
|
+
}
|
|
462
|
+
sheet.colProps = colProps;
|
|
463
|
+
}
|
|
464
|
+
const view = {};
|
|
465
|
+
if (options.rightToLeft) view.rightToLeft = true;
|
|
466
|
+
if (options.freezeHeader && first && first.headerRows > 0) view.freeze = { rows: first.lastHeaderRow + 1 };
|
|
467
|
+
if (Object.keys(view).length) sheet.view = view;
|
|
468
|
+
if (options.autoFilter && first && first.headerRows > 0) sheet.autoFilter = range(first.lastHeaderRow, first.firstCol, first.lastDataRow, first.lastCol);
|
|
469
|
+
return sheet;
|
|
470
|
+
}
|
|
471
|
+
function sheetName(options) {
|
|
472
|
+
const name = options.name ?? "Sheet1";
|
|
473
|
+
const problem = validateSheetName(name);
|
|
474
|
+
if (problem) throw new ValidationError("INVALID_SHEET_NAME", `Sheet name ${JSON.stringify(name)} is invalid (${problem}).`, { details: {
|
|
475
|
+
sheet: name,
|
|
476
|
+
problem
|
|
477
|
+
} });
|
|
478
|
+
return name;
|
|
479
|
+
}
|
|
480
|
+
function originOf(options) {
|
|
481
|
+
if (options.origin === void 0) return {
|
|
482
|
+
row: 0,
|
|
483
|
+
col: 0
|
|
484
|
+
};
|
|
485
|
+
return decodeCell(options.origin);
|
|
486
|
+
}
|
|
487
|
+
const newGrid = () => ({
|
|
488
|
+
rows: [],
|
|
489
|
+
merges: [],
|
|
490
|
+
widths: /* @__PURE__ */ new Map(),
|
|
491
|
+
measured: /* @__PURE__ */ new Map(),
|
|
492
|
+
autoCols: /* @__PURE__ */ new Set(),
|
|
493
|
+
hidden: /* @__PURE__ */ new Set()
|
|
494
|
+
});
|
|
495
|
+
/** Builds a sheet from `{ columns, data }`. */
|
|
496
|
+
function fromDataset(dataset, options = {}) {
|
|
497
|
+
const name = sheetName(options);
|
|
498
|
+
const origin = originOf(options);
|
|
499
|
+
const g = newGrid();
|
|
500
|
+
return finish(g, options, layoutBlock(g, dataset, options, origin.row, origin.col, name), name);
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Stacks several datasets on one sheet (replaces the old xSteps/ySteps).
|
|
504
|
+
* Each block starts `gap` empty rows (default 1) below the previous one, or
|
|
505
|
+
* `offset.rows` rows when given, and `offset.cols` columns right of the
|
|
506
|
+
* origin. Freeze and filter apply to the first block with header rows.
|
|
507
|
+
*/
|
|
508
|
+
function fromDatasets(blocks, options = {}) {
|
|
509
|
+
if (!Array.isArray(blocks)) throw columnError("fromDatasets needs an array of datasets.");
|
|
510
|
+
const name = sheetName(options);
|
|
511
|
+
const origin = originOf(options);
|
|
512
|
+
const gap = options.gap ?? 1;
|
|
513
|
+
if (!Number.isInteger(gap) || gap < 0) throw columnError(`gap must be a non-negative integer, got ${String(gap)}.`);
|
|
514
|
+
const g = newGrid();
|
|
515
|
+
let first;
|
|
516
|
+
let nextRow = origin.row;
|
|
517
|
+
blocks.forEach((block, i) => {
|
|
518
|
+
const offRows = block.offset?.rows;
|
|
519
|
+
const offCols = block.offset?.cols ?? 0;
|
|
520
|
+
const top = i === 0 ? origin.row + (offRows ?? 0) : nextRow + (offRows ?? gap);
|
|
521
|
+
const result = layoutBlock(g, block, options, top, origin.col + offCols, name);
|
|
522
|
+
if (!first && result.headerRows > 0) first = result;
|
|
523
|
+
nextRow = result.lastRow + 1;
|
|
524
|
+
});
|
|
525
|
+
return finish(g, options, first, name);
|
|
526
|
+
}
|
|
527
|
+
const SUBTOTAL_FORMULA = /^\s*=?\s*SUBTOTAL\s*\(/i;
|
|
528
|
+
/** A row with at least one formula, all of them SUBTOTAL(...): the totals row fromDataset writes. */
|
|
529
|
+
function isTotalsRow(row) {
|
|
530
|
+
let formulas = 0;
|
|
531
|
+
for (const c of row) {
|
|
532
|
+
if (!isCellObject(c) || !c.formula) continue;
|
|
533
|
+
if (!SUBTOTAL_FORMULA.test(c.formula)) return false;
|
|
534
|
+
formulas++;
|
|
535
|
+
}
|
|
536
|
+
return formulas > 0;
|
|
537
|
+
}
|
|
538
|
+
function usedRange(sheet) {
|
|
539
|
+
let minR = 1e400, maxR = -1, minC = 1e400, maxC = -1;
|
|
540
|
+
sheet.rows.forEach((row, r) => row?.forEach((c, col) => {
|
|
541
|
+
if (c === void 0 || c === null) return;
|
|
542
|
+
minR = Math.min(minR, r);
|
|
543
|
+
maxR = Math.max(maxR, r);
|
|
544
|
+
minC = Math.min(minC, col);
|
|
545
|
+
maxC = Math.max(maxC, col);
|
|
546
|
+
}));
|
|
547
|
+
return maxR < 0 ? void 0 : {
|
|
548
|
+
start: {
|
|
549
|
+
row: minR,
|
|
550
|
+
col: minC
|
|
551
|
+
},
|
|
552
|
+
end: {
|
|
553
|
+
row: maxR,
|
|
554
|
+
col: maxC
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Reads a sheet back into `{ columns, data }` (import direction). Keys come
|
|
560
|
+
* from the header text, deduplicated with _2, _3...; an empty header gives the
|
|
561
|
+
* column letter. Empty rows are skipped. Rows are null-prototype objects, so
|
|
562
|
+
* a header named __proto__ in an untrusted file is just a key.
|
|
563
|
+
*/
|
|
564
|
+
function toDataset(sheet, options = {}) {
|
|
565
|
+
const { columns, data } = toDatasetDetailed(sheet, options);
|
|
566
|
+
return {
|
|
567
|
+
columns: columns.map(({ title, key }) => ({
|
|
568
|
+
title,
|
|
569
|
+
key
|
|
570
|
+
})),
|
|
571
|
+
data
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
/** @internal */
|
|
575
|
+
function toDatasetDetailed(sheet, options = {}) {
|
|
576
|
+
const s = sheet;
|
|
577
|
+
const rng = options.range ? decodeRange(options.range) : s.dimension ? decodeRange(s.dimension) : usedRange(s);
|
|
578
|
+
if (!rng) return {
|
|
579
|
+
columns: [],
|
|
580
|
+
data: [],
|
|
581
|
+
rowNumbers: [],
|
|
582
|
+
totalsSkipped: false,
|
|
583
|
+
range: void 0
|
|
584
|
+
};
|
|
585
|
+
const headerRow = options.headerRow ?? 0;
|
|
586
|
+
if (headerRow !== false && (!Number.isInteger(headerRow) || headerRow < 0)) throw columnError(`headerRow must be a non-negative integer or false, got ${String(headerRow)}.`);
|
|
587
|
+
const headerRows = options.headerRows ?? 1;
|
|
588
|
+
if (!Number.isInteger(headerRows) || headerRows < 1) throw columnError(`headerRows must be a positive integer, got ${String(headerRows)}.`);
|
|
589
|
+
const join = options.join ?? " / ";
|
|
590
|
+
if (typeof join !== "string") throw new TypeError("join must be a string");
|
|
591
|
+
const asCell = options.values === "cell";
|
|
592
|
+
const titleOf = headerRow === false ? void 0 : headerRows === 1 ? (c) => cellText(s.rows[headerRow]?.[c]).trim() : multiRowTitles(s, headerRow, headerRows, join);
|
|
593
|
+
const columns = [];
|
|
594
|
+
const used = /* @__PURE__ */ new Map();
|
|
595
|
+
for (let c = rng.start.col; c <= rng.end.col; c++) {
|
|
596
|
+
const letter = encodeCol(c);
|
|
597
|
+
const title = titleOf ? titleOf(c) : letter;
|
|
598
|
+
const base = title === "" ? letter : title;
|
|
599
|
+
const n = (used.get(base) ?? 0) + 1;
|
|
600
|
+
used.set(base, n);
|
|
601
|
+
columns.push({
|
|
602
|
+
title,
|
|
603
|
+
key: n === 1 ? base : `${base}_${n}`,
|
|
604
|
+
letter
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
const data = [];
|
|
608
|
+
const rowNumbers = [];
|
|
609
|
+
let lastRaw;
|
|
610
|
+
const firstData = headerRow === false ? rng.start.row : Math.max(rng.start.row, headerRow + headerRows);
|
|
611
|
+
for (let r = firstData; r <= rng.end.row; r++) {
|
|
612
|
+
const row = s.rows[r];
|
|
613
|
+
if (!row) continue;
|
|
614
|
+
let any = false;
|
|
615
|
+
const obj = Object.create(null);
|
|
616
|
+
columns.forEach(({ key }, k) => {
|
|
617
|
+
const c = row[rng.start.col + k];
|
|
618
|
+
if (!(c === void 0 || c === null || isCellObject(c) && (c.value === void 0 || c.value === null) && !c.formula)) any = true;
|
|
619
|
+
obj[key] = asCell ? c === void 0 ? null : isCellObject(c) ? c : { value: c } : c === void 0 || c === null ? null : isCellObject(c) ? c.value ?? null : c;
|
|
620
|
+
});
|
|
621
|
+
if (any) {
|
|
622
|
+
data.push(obj);
|
|
623
|
+
rowNumbers.push(r + 1);
|
|
624
|
+
lastRaw = row.slice(rng.start.col, rng.end.col + 1);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
const skipTotals = options.skipTotals ?? "auto";
|
|
628
|
+
let totalsSkipped = false;
|
|
629
|
+
if (data.length && (skipTotals === true || skipTotals === "auto" && lastRaw && isTotalsRow(lastRaw))) {
|
|
630
|
+
data.pop();
|
|
631
|
+
rowNumbers.pop();
|
|
632
|
+
totalsSkipped = true;
|
|
633
|
+
}
|
|
634
|
+
return {
|
|
635
|
+
columns,
|
|
636
|
+
data,
|
|
637
|
+
rowNumbers,
|
|
638
|
+
totalsSkipped,
|
|
639
|
+
range: encodeRange(rng)
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Titles of a header spanning several rows: the text of each row joined,
|
|
644
|
+
* with merged cells expanded (a group title merged across columns prefixes
|
|
645
|
+
* each of them) and a cell merged down through the rows counted once.
|
|
646
|
+
*/
|
|
647
|
+
function multiRowTitles(s, top, count, join) {
|
|
648
|
+
const bottom = top + count - 1;
|
|
649
|
+
const merges = (s.merges ?? []).map((m) => decodeRange(m)).filter((m) => m.start.row <= bottom && m.end.row >= top);
|
|
650
|
+
return (c) => {
|
|
651
|
+
const parts = [];
|
|
652
|
+
let last;
|
|
653
|
+
for (let r = top; r <= bottom; r++) {
|
|
654
|
+
const m = merges.find((x) => r >= x.start.row && r <= x.end.row && c >= x.start.col && c <= x.end.col);
|
|
655
|
+
const id = m ?? `${r}`;
|
|
656
|
+
if (id === last) continue;
|
|
657
|
+
last = id;
|
|
658
|
+
const text = cellText(m ? s.rows[m.start.row]?.[m.start.col] : s.rows[r]?.[c]).trim();
|
|
659
|
+
if (text !== "") parts.push(text);
|
|
660
|
+
}
|
|
661
|
+
return parts.join(join);
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
export { toDatasetDetailed as i, fromDatasets as n, toDataset as r, fromDataset as t };
|