@office-open/xlsx 0.10.15 → 0.11.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.
@@ -1,4106 +0,0 @@
1
- import { a as SharedStrings } from "./comments-CUChd469.mjs";
2
- import { attr, attrNum, attrs, children, escapeXml, findChild, stringify, textOf } from "@office-open/xml";
3
- import { ChartCollection, Media, Relationships, convertToEmu, convertToInch, derivePasswordHash } from "@office-open/core";
4
- //#region src/parts/styles.ts
5
- function fontKey(f) {
6
- return `b${f.bold ? 1 : 0}i${f.italic ? 1 : 0}u${f.underline ? 1 : 0}s${f.strike ? 1 : 0}z${f.size ?? 0}c${f.color ?? ""}n${f.font ?? ""}cs${f.charset ?? ""}fm${f.family ?? ""}co${f.condense ? 1 : 0}ex${f.extend ? 1 : 0}va${f.vertAlign ?? ""}sc${f.scheme ?? ""}sh${f.shadow ? 1 : 0}ol${f.outline ? 1 : 0}`;
7
- }
8
- function fillKey(f) {
9
- return `t${f.type ?? ""}c${f.color ?? ""}p${f.patternType ?? ""}bg${f.bgColor ?? ""}g${f.stops?.map((s) => `${s.position}_${s.color}`).join("|") ?? ""}`;
10
- }
11
- function borderKey(b) {
12
- const sk = (o) => `${o?.style ?? ""}_${o?.color ?? ""}`;
13
- return `t${sk(b.top)}b${sk(b.bottom)}l${sk(b.left)}r${sk(b.right)}d${sk(b.diagonal)}du${b.diagonalUp ? 1 : 0}dd${b.diagonalDown ? 1 : 0}st${sk(b.start)}en${sk(b.end)}v${sk(b.vertical)}h${sk(b.horizontal)}`;
14
- }
15
- const BUILTIN_NUMFMTS = {
16
- General: 0,
17
- "0": 1,
18
- "0.00": 2,
19
- "#,##0": 3,
20
- "#,##0.00": 4,
21
- "0%": 9,
22
- "0.00%": 10,
23
- "0.00E+00": 11,
24
- "mm-dd-yy": 14,
25
- "d-mmm-yy": 15,
26
- "d-mmm": 16,
27
- "mmm-yy": 17,
28
- "h:mm AM/PM": 18,
29
- "h:mm:ss AM/PM": 19,
30
- "h:mm": 20,
31
- "h:mm:ss": 21,
32
- "m/d/yy h:mm": 22,
33
- "#,##0 ;(#,##0)": 37,
34
- "#,##0 ;[Red](#,##0)": 38,
35
- "#,##0.00;(#,##0.00)": 39,
36
- "#,##0.00;[Red](#,##0.00)": 40,
37
- "mm:ss": 45,
38
- "[h]:mm:ss": 46,
39
- "mmss.0": 47,
40
- "##0.0E+0": 48,
41
- "@": 49
42
- };
43
- var Styles = class {
44
- fonts = [{
45
- size: 11,
46
- font: "Calibri"
47
- }];
48
- fontKeys = /* @__PURE__ */ new Map();
49
- fills = [{ patternType: "none" }, { patternType: "gray125" }];
50
- fillKeys = /* @__PURE__ */ new Map();
51
- borders = [{}];
52
- borderKeys = /* @__PURE__ */ new Map();
53
- customNumFmts = /* @__PURE__ */ new Map();
54
- nextCustomNumFmtId = 164;
55
- cellXfs = [{
56
- fontId: 0,
57
- fillId: 0,
58
- borderId: 0,
59
- numFmtId: 0
60
- }];
61
- cellXfKeys = /* @__PURE__ */ new Map();
62
- dxfs = [];
63
- colors;
64
- tableStyles;
65
- /** Custom cell styles (CT_CellStyles) */
66
- customCellStyles;
67
- /** Style sheet extensions (CT_ExtensionList) */
68
- styleExtensions;
69
- constructor() {
70
- this.fontKeys.set(fontKey(this.fonts[0]), 0);
71
- this.fillKeys.set(fillKey(this.fills[0]), 0);
72
- this.fillKeys.set(fillKey(this.fills[1]), 1);
73
- this.borderKeys.set(borderKey(this.borders[0]), 0);
74
- this.cellXfKeys.set(this.cellXfKey(this.cellXfs[0]), 0);
75
- }
76
- /**
77
- * Register a style and return its index (for the cell `s` attribute).
78
- * Deduplicates across fonts, fills, borders, numFmts, and cellXfs.
79
- */
80
- register(opts) {
81
- const xf = {
82
- fontId: this.registerFont(opts.font),
83
- fillId: this.registerFill(opts.fill),
84
- borderId: this.registerBorder(opts.border),
85
- numFmtId: this.registerNumFmt(opts.numFmt),
86
- alignment: opts.alignment,
87
- quotePrefix: opts.quotePrefix,
88
- pivotButton: opts.pivotButton,
89
- applyProtection: opts.applyProtection,
90
- protection: opts.protection
91
- };
92
- const key = this.cellXfKey(xf);
93
- const existing = this.cellXfKeys.get(key);
94
- if (existing !== void 0) return existing;
95
- const idx = this.cellXfs.length;
96
- this.cellXfs.push(xf);
97
- this.cellXfKeys.set(key, idx);
98
- return idx;
99
- }
100
- /**
101
- * Register a differential format and return its index (dxfId).
102
- * Used by conditional formatting rules.
103
- */
104
- registerDxf(opts) {
105
- const idx = this.dxfs.length;
106
- this.dxfs.push(opts);
107
- return idx;
108
- }
109
- /**
110
- * Set color palette (indexed colors and MRU colors).
111
- */
112
- setColors(opts) {
113
- this.colors = opts;
114
- }
115
- setTableStyles(styles) {
116
- this.tableStyles = styles;
117
- }
118
- setExtensions(extensions) {
119
- this.styleExtensions = extensions;
120
- }
121
- setCustomCellStyles(styles) {
122
- this.customCellStyles = styles;
123
- }
124
- /**
125
- * Expose internal state for descriptor-based XML generation.
126
- * The descriptor reads this snapshot to produce xl/styles.xml.
127
- */
128
- toDescriptorOptions() {
129
- return {
130
- customNumFmts: new Map(this.customNumFmts),
131
- fonts: [...this.fonts],
132
- fills: [...this.fills],
133
- borders: [...this.borders],
134
- cellXfs: [...this.cellXfs],
135
- dxfs: [...this.dxfs],
136
- colors: this.colors,
137
- tableStyles: this.tableStyles,
138
- customCellStyles: this.customCellStyles,
139
- styleExtensions: this.styleExtensions
140
- };
141
- }
142
- registerFont(opts) {
143
- if (!opts) return 0;
144
- const key = fontKey(opts);
145
- const existing = this.fontKeys.get(key);
146
- if (existing !== void 0) return existing;
147
- const idx = this.fonts.length;
148
- this.fonts.push(opts);
149
- this.fontKeys.set(key, idx);
150
- return idx;
151
- }
152
- registerFill(opts) {
153
- if (!opts) return 0;
154
- const key = fillKey(opts);
155
- const existing = this.fillKeys.get(key);
156
- if (existing !== void 0) return existing;
157
- const idx = this.fills.length;
158
- this.fills.push(opts);
159
- this.fillKeys.set(key, idx);
160
- return idx;
161
- }
162
- registerBorder(opts) {
163
- if (!opts) return 0;
164
- const key = borderKey(opts);
165
- const existing = this.borderKeys.get(key);
166
- if (existing !== void 0) return existing;
167
- const idx = this.borders.length;
168
- this.borders.push(opts);
169
- this.borderKeys.set(key, idx);
170
- return idx;
171
- }
172
- registerNumFmt(fmt) {
173
- if (!fmt) return 0;
174
- const builtin = BUILTIN_NUMFMTS[fmt];
175
- if (builtin !== void 0) return builtin;
176
- const existing = this.customNumFmts.get(fmt);
177
- if (existing !== void 0) return existing;
178
- const id = this.nextCustomNumFmtId++;
179
- this.customNumFmts.set(fmt, id);
180
- return id;
181
- }
182
- cellXfKey(xf) {
183
- const a = xf.alignment;
184
- const ak = a ? `h${a.horizontal ?? ""}v${a.vertical ?? ""}w${a.wrapText ? 1 : 0}r${a.textRotation ?? ""}i${a.indent ?? ""}ri${a.relativeIndent ?? ""}jl${a.justifyLastLine ? 1 : 0}st${a.shrinkToFit ? 1 : 0}ro${a.readingOrder ?? ""}` : "";
185
- const pr = xf.protection;
186
- const pk = pr ? `l${pr.locked ?? ""}h${pr.hidden ?? ""}` : "";
187
- return `${xf.fontId}|${xf.fillId}|${xf.borderId}|${xf.numFmtId}|${ak}|qp${xf.quotePrefix ? 1 : 0}|pb${xf.pivotButton ? 1 : 0}|${pk}`;
188
- }
189
- /**
190
- * Zero-allocation fast path: directly concatenate XML string.
191
- * Bypasses the intermediate object tree entirely.
192
- */
193
- /** Serialize to xl/styles.xml content (without XML declaration). */
194
- serialize() {
195
- const p = ["<styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">"];
196
- if (this.customNumFmts.size > 0) {
197
- p.push(`<numFmts count="${this.customNumFmts.size}">`);
198
- for (const [fmt, id] of this.customNumFmts) p.push(`<numFmt numFmtId="${id}" formatCode="${escapeXml(fmt)}"/>`);
199
- p.push("</numFmts>");
200
- }
201
- p.push(`<fonts count="${this.fonts.length}">`);
202
- for (const f of this.fonts) p.push(`<font>${this.fontXmlStr(f)}</font>`);
203
- p.push("</fonts>");
204
- p.push(`<fills count="${this.fills.length}">`);
205
- for (const f of this.fills) if (f.type === "gradient" && f.stops && f.stops.length > 0) {
206
- const gfAttrs = {};
207
- if (f.gradientType && f.gradientType !== "linear") gfAttrs.type = f.gradientType;
208
- if (f.gradientDegree !== void 0) gfAttrs.degree = f.gradientDegree;
209
- if (f.gradientLeft !== void 0) gfAttrs.left = f.gradientLeft;
210
- if (f.gradientRight !== void 0) gfAttrs.right = f.gradientRight;
211
- if (f.gradientTop !== void 0) gfAttrs.top = f.gradientTop;
212
- if (f.gradientBottom !== void 0) gfAttrs.bottom = f.gradientBottom;
213
- const stopParts = f.stops.map((s) => `<stop position="${s.position}"><color rgb="FF${s.color}"/></stop>`).join("");
214
- p.push(`<fill><gradientFill${attrs(gfAttrs)}>${stopParts}</gradientFill></fill>`);
215
- } else {
216
- const patternAttrs = attrs({ patternType: f.patternType ?? "solid" });
217
- const colorContent = (f.color ? `<fgColor rgb="FF${f.color}"/>` : f.colorIndexed !== void 0 ? `<fgColor indexed="${f.colorIndexed}"/>` : "") + (f.bgColor ? `<bgColor rgb="FF${f.bgColor}"/>` : "");
218
- p.push(colorContent ? `<fill><patternFill${patternAttrs}>${colorContent}</patternFill></fill>` : `<fill><patternFill${patternAttrs}/></fill>`);
219
- }
220
- p.push("</fills>");
221
- p.push(`<borders count="${this.borders.length}">`);
222
- for (const b of this.borders) {
223
- const bAttrs = [];
224
- if (b.diagonalUp) bAttrs.push("diagonalUp=\"1\"");
225
- if (b.diagonalDown) bAttrs.push("diagonalDown=\"1\"");
226
- const bAttr = bAttrs.length ? ` ${bAttrs.join(" ")}` : "";
227
- p.push(`<border${bAttr}>${this.borderXmlStr(b)}</border>`);
228
- }
229
- p.push("</borders>");
230
- p.push("<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>");
231
- p.push(`<cellXfs count="${this.cellXfs.length}">`);
232
- for (const xf of this.cellXfs) {
233
- const xAttrs = {
234
- numFmtId: xf.numFmtId,
235
- fontId: xf.fontId,
236
- fillId: xf.fillId,
237
- borderId: xf.borderId,
238
- xfId: 0
239
- };
240
- if (xf.alignment) xAttrs.applyAlignment = 1;
241
- if (xf.fontId > 0) xAttrs.applyFont = 1;
242
- if (xf.fillId > 0) xAttrs.applyFill = 1;
243
- if (xf.borderId > 0) xAttrs.applyBorder = 1;
244
- if (xf.numFmtId > 0) xAttrs.applyNumberFormat = 1;
245
- if (xf.quotePrefix) xAttrs.quotePrefix = 1;
246
- if (xf.pivotButton) xAttrs.pivotButton = 1;
247
- if (xf.applyProtection) xAttrs.applyProtection = 1;
248
- if (xf.protection) xAttrs.applyProtection = xAttrs.applyProtection ?? 1;
249
- const inner = (xf.alignment ? this.alignmentXmlStr(xf.alignment) : "") + (xf.protection ? this.protectionXmlStr(xf.protection) : "");
250
- p.push(inner ? `<xf${attrs(xAttrs)}>${inner}</xf>` : `<xf${attrs(xAttrs)}/>`);
251
- }
252
- p.push("</cellXfs>");
253
- if (this.customCellStyles && this.customCellStyles.length > 0) {
254
- const hasNormal = this.customCellStyles.some((cs) => cs.builtinId === 0 && cs.name === "Normal");
255
- const csParts = [`<cellStyles ${[`count="${this.customCellStyles.length + (hasNormal ? 0 : 1)}"`].join(" ")}>`];
256
- if (!hasNormal) csParts.push("<cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/>");
257
- for (const cs of this.customCellStyles) {
258
- const attrs = [`name="${escapeXml(cs.name)}"`, `xfId="${cs.xfId}"`];
259
- if (cs.builtinId !== void 0) attrs.push(`builtinId="${cs.builtinId}"`);
260
- if (cs.customBuiltin) attrs.push("customBuiltin=\"1\"");
261
- if (cs.iLevel !== void 0) attrs.push(`iLevel="${cs.iLevel}"`);
262
- if (cs.hidden) attrs.push("hidden=\"1\"");
263
- csParts.push(`<cellStyle ${attrs.join(" ")}/>`);
264
- }
265
- csParts.push("</cellStyles>");
266
- p.push(csParts.join(""));
267
- } else p.push("<cellStyles count=\"1\"><cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/></cellStyles>");
268
- if (this.dxfs.length > 0) {
269
- p.push(`<dxfs count="${this.dxfs.length}">`);
270
- for (const dxf of this.dxfs) {
271
- const dParts = [];
272
- if (dxf.font) dParts.push(`<font>${this.fontXmlStr(dxf.font)}</font>`);
273
- if (dxf.fill) {
274
- const bgColor = dxf.fill.color ? `<bgColor rgb="FF${dxf.fill.color}"/>` : "";
275
- const patAttrs = attrs({ patternType: dxf.fill.patternType ?? "solid" });
276
- dParts.push(`<fill><patternFill${patAttrs}>${bgColor}</patternFill></fill>`);
277
- }
278
- if (dxf.numFmt) dParts.push(`<numFmt formatCode="${escapeXml(dxf.numFmt)}"/>`);
279
- if (dxf.border) dParts.push(`<border>${this.borderXmlStr(dxf.border)}</border>`);
280
- if (dParts.length > 0) p.push(`<dxf>${dParts.join("")}</dxf>`);
281
- else p.push("<dxf/>");
282
- }
283
- p.push("</dxfs>");
284
- } else p.push("<dxfs count=\"0\"/>");
285
- if (this.tableStyles && this.tableStyles.length > 0) {
286
- const tsParts = [`<tableStyles count="${this.tableStyles.length}" defaultTableStyle="TableStyleMedium2" defaultPivotStyle="PivotStyleLight16">`];
287
- for (const ts of this.tableStyles) {
288
- const tsAttrs = [`name="${escapeXml(ts.name)}"`];
289
- if (ts.pivot) tsAttrs.push("pivot=\"1\"");
290
- if (ts.elements && ts.elements.length > 0) {
291
- tsParts.push(`<tableStyle ${tsAttrs.join(" ")}>`);
292
- for (const el of ts.elements) {
293
- const elAttrs = [`type="${el.type}"`];
294
- if (el.dxfId !== void 0) elAttrs.push(`dxfId="${el.dxfId}"`);
295
- if (el.button) elAttrs.push("button=\"1\"");
296
- tsParts.push(`<tableStyleElement ${elAttrs.join(" ")}/>`);
297
- }
298
- tsParts.push("</tableStyle>");
299
- } else tsParts.push(`<tableStyle ${tsAttrs.join(" ")}/>`);
300
- }
301
- tsParts.push("</tableStyles>");
302
- p.push(tsParts.join(""));
303
- } else p.push("<tableStyles count=\"0\" defaultTableStyle=\"TableStyleMedium2\" defaultPivotStyle=\"PivotStyleLight16\"/>");
304
- if (this.colors) {
305
- const c = this.colors;
306
- const colorParts = ["<colors>"];
307
- if (c.indexedColors && c.indexedColors.length > 0) {
308
- colorParts.push("<indexedColors>");
309
- for (const ic of c.indexedColors) colorParts.push(`<rgbColor rgb="${ic.rgb}"/>`);
310
- colorParts.push("</indexedColors>");
311
- }
312
- if (c.mruColors && c.mruColors.length > 0) {
313
- colorParts.push("<mruColors>");
314
- for (const mc of c.mruColors) colorParts.push(`<color rgb="FF${mc}"/>`);
315
- colorParts.push("</mruColors>");
316
- }
317
- colorParts.push("</colors>");
318
- p.push(colorParts.join(""));
319
- }
320
- if (this.styleExtensions && this.styleExtensions.length > 0) {
321
- const extParts = ["<extLst>"];
322
- for (const ext of this.styleExtensions) if (ext.content) extParts.push(`<ext uri="${ext.uri}">${ext.content}</ext>`);
323
- else extParts.push(`<ext uri="${ext.uri}"/>`);
324
- extParts.push("</extLst>");
325
- p.push(extParts.join(""));
326
- } else p.push("<extLst/>");
327
- p.push("</styleSheet>");
328
- return p.join("");
329
- }
330
- fontXmlStr(f) {
331
- const parts = [];
332
- if (f.bold) parts.push("<b/>");
333
- if (f.italic) parts.push("<i/>");
334
- if (f.underline) parts.push("<u/>");
335
- if (f.strike) parts.push("<strike/>");
336
- if (f.outline) parts.push("<outline/>");
337
- if (f.shadow) parts.push("<shadow/>");
338
- if (f.condense) parts.push("<condense/>");
339
- if (f.extend) parts.push("<extend/>");
340
- if (f.size) parts.push(`<sz val="${f.size}"/>`);
341
- if (f.color) parts.push(`<color rgb="FF${f.color}"/>`);
342
- if (f.font) parts.push(`<name val="${escapeXml(f.font)}"/>`);
343
- if (f.charset !== void 0) parts.push(`<charset val="${f.charset}"/>`);
344
- if (f.family !== void 0) parts.push(`<family val="${f.family}"/>`);
345
- if (f.vertAlign) parts.push(`<vertAlign val="${f.vertAlign}"/>`);
346
- if (f.scheme) parts.push(`<scheme val="${f.scheme}"/>`);
347
- return parts.join("");
348
- }
349
- borderXmlStr(b) {
350
- const parts = [];
351
- const renderSide = (name, opts, required = true) => {
352
- if (opts && opts.style && opts.style !== "none") {
353
- const colorStr = opts.color ? `<color rgb="FF${opts.color}"/>` : "";
354
- parts.push(`<${name} style="${opts.style}">${colorStr}</${name}>`);
355
- } else if (required) parts.push(`<${name}/>`);
356
- };
357
- for (const side of [
358
- "left",
359
- "right",
360
- "top",
361
- "bottom",
362
- "diagonal",
363
- "vertical",
364
- "horizontal"
365
- ]) renderSide(side, b[side]);
366
- renderSide("start", b.start, false);
367
- renderSide("end", b.end, false);
368
- return parts.join("");
369
- }
370
- alignmentXmlStr(a) {
371
- const aAttrs = {};
372
- if (a.horizontal) aAttrs.horizontal = a.horizontal;
373
- if (a.vertical) aAttrs.vertical = a.vertical;
374
- if (a.wrapText) aAttrs.wrapText = 1;
375
- if (a.textRotation !== void 0) aAttrs.textRotation = a.textRotation;
376
- if (a.indent !== void 0) aAttrs.indent = a.indent;
377
- if (a.relativeIndent !== void 0) aAttrs.relativeIndent = a.relativeIndent;
378
- if (a.justifyLastLine) aAttrs.justifyLastLine = 1;
379
- if (a.shrinkToFit) aAttrs.shrinkToFit = 1;
380
- if (a.readingOrder !== void 0) aAttrs.readingOrder = a.readingOrder;
381
- return `<alignment${attrs(aAttrs)}/>`;
382
- }
383
- protectionXmlStr(pr) {
384
- const prAttrs = {};
385
- if (pr.locked !== void 0) prAttrs.locked = pr.locked ? 1 : 0;
386
- if (pr.hidden !== void 0) prAttrs.hidden = pr.hidden ? 1 : 0;
387
- return `<protection${attrs(prAttrs)}/>`;
388
- }
389
- };
390
- const stylesDesc = {
391
- kind: "custom",
392
- stringify(opts, _ctx) {
393
- return opts.styles.serialize();
394
- },
395
- parse(el, _ctx) {
396
- const result = {};
397
- const numFmtsEl = findChild(el, "numFmts");
398
- if (numFmtsEl) {
399
- const numFmtById = /* @__PURE__ */ new Map();
400
- for (const nf of numFmtsEl.elements ?? []) {
401
- if (nf.name !== "numFmt") continue;
402
- const id = attrNum(nf, "numFmtId");
403
- const code = attr(nf, "formatCode");
404
- if (id !== void 0 && code) numFmtById.set(id, code);
405
- }
406
- result.customNumFmtById = numFmtById;
407
- }
408
- const fontsEl = findChild(el, "fonts");
409
- if (fontsEl) {
410
- const fonts = [];
411
- for (const f of fontsEl.elements ?? []) {
412
- if (f.name !== "font") continue;
413
- fonts.push(parseFont(f));
414
- }
415
- result.fonts = fonts;
416
- }
417
- const fillsEl = findChild(el, "fills");
418
- if (fillsEl) {
419
- const fills = [];
420
- for (const f of fillsEl.elements ?? []) {
421
- if (f.name !== "fill") continue;
422
- fills.push(parseFill(f));
423
- }
424
- result.fills = fills;
425
- }
426
- const bordersEl = findChild(el, "borders");
427
- if (bordersEl) {
428
- const borders = [];
429
- for (const b of bordersEl.elements ?? []) {
430
- if (b.name !== "border") continue;
431
- borders.push(parseBorder(b));
432
- }
433
- result.borders = borders;
434
- }
435
- const cellStyleXfsEl = findChild(el, "cellStyleXfs");
436
- if (cellStyleXfsEl) {
437
- const xfs = [];
438
- for (const xf of cellStyleXfsEl.elements ?? []) {
439
- if (xf.name !== "xf") continue;
440
- const style = {};
441
- const fontId = attrNum(xf, "fontId");
442
- const fillId = attrNum(xf, "fillId");
443
- const borderId = attrNum(xf, "borderId");
444
- const numFmtId = attrNum(xf, "numFmtId");
445
- if (fontId !== void 0) style.fontId = fontId;
446
- if (fillId !== void 0) style.fillId = fillId;
447
- if (borderId !== void 0) style.borderId = borderId;
448
- if (numFmtId !== void 0) style.numFmtId = numFmtId;
449
- xfs.push(style);
450
- }
451
- result.cellStyleXfs = xfs;
452
- }
453
- const cellXfsEl = findChild(el, "cellXfs");
454
- if (cellXfsEl) {
455
- const xfs = [];
456
- for (const xf of cellXfsEl.elements ?? []) {
457
- if (xf.name !== "xf") continue;
458
- const fontId = attrNum(xf, "fontId") ?? 0;
459
- const fillId = attrNum(xf, "fillId") ?? 0;
460
- const borderId = attrNum(xf, "borderId") ?? 0;
461
- const numFmtId = attrNum(xf, "numFmtId") ?? 0;
462
- const alignmentEl = findChild(xf, "alignment");
463
- const alignment = alignmentEl ? parseAlignment(alignmentEl) : void 0;
464
- const protectionEl = findChild(xf, "protection");
465
- const protection = protectionEl ? parseProtection(protectionEl) : void 0;
466
- const style = {};
467
- if (fontId > 0) style.fontId = fontId;
468
- if (fillId > 0) style.fillId = fillId;
469
- if (borderId > 0) style.borderId = borderId;
470
- if (numFmtId > 0) style.numFmtId = numFmtId;
471
- if (alignment) style.alignment = alignment;
472
- if (protection) style.protection = protection;
473
- if (attr(xf, "quotePrefix") === "1") style.quotePrefix = true;
474
- if (attr(xf, "pivotButton") === "1") style.pivotButton = true;
475
- xfs.push(style);
476
- }
477
- result.cellXfs = xfs;
478
- }
479
- const cellStylesEl = findChild(el, "cellStyles");
480
- if (cellStylesEl) {
481
- const styles = [];
482
- for (const cs of cellStylesEl.elements ?? []) {
483
- if (cs.name !== "cellStyle") continue;
484
- const style = {};
485
- if (attr(cs, "name")) style.name = attr(cs, "name");
486
- const xfId = attrNum(cs, "xfId");
487
- if (xfId !== void 0) style.xfId = xfId;
488
- const builtinId = attrNum(cs, "builtinId");
489
- if (builtinId !== void 0) style.builtinId = builtinId;
490
- if (attr(cs, "customBuiltin") === "1") style.customBuiltin = true;
491
- if (attr(cs, "hidden") === "1") style.hidden = true;
492
- const iLevel = attrNum(cs, "iLevel");
493
- if (iLevel !== void 0) style.iLevel = iLevel;
494
- styles.push(style);
495
- }
496
- result.customCellStyles = styles;
497
- }
498
- const dxfsEl = findChild(el, "dxfs");
499
- if (dxfsEl) {
500
- const dxfs = [];
501
- for (const dxf of dxfsEl.elements ?? []) {
502
- if (dxf.name !== "dxf") continue;
503
- const d = {};
504
- const fontEl = findChild(dxf, "font");
505
- if (fontEl) d.font = parseFont(fontEl);
506
- const fillEl = findChild(dxf, "fill");
507
- if (fillEl) d.fill = parseFill(fillEl);
508
- const borderEl = findChild(dxf, "border");
509
- if (borderEl) d.border = parseBorder(borderEl);
510
- const numFmtEl = findChild(dxf, "numFmt");
511
- if (numFmtEl && attr(numFmtEl, "formatCode")) d.numFmt = attr(numFmtEl, "formatCode");
512
- dxfs.push(d);
513
- }
514
- result.dxfs = dxfs;
515
- }
516
- const tableStylesEl = findChild(el, "tableStyles");
517
- if (tableStylesEl?.attributes) {
518
- const ts = {};
519
- if (attr(tableStylesEl, "count") !== void 0) ts.count = attrNum(tableStylesEl, "count") ?? 0;
520
- if (attr(tableStylesEl, "defaultTableStyle")) ts.defaultTableStyle = attr(tableStylesEl, "defaultTableStyle");
521
- if (attr(tableStylesEl, "defaultPivotStyle")) ts.defaultPivotStyle = attr(tableStylesEl, "defaultPivotStyle");
522
- const customStyles = [];
523
- for (const tse of tableStylesEl.elements ?? []) {
524
- if (tse.name !== "tableStyle") continue;
525
- const style = {};
526
- if (attr(tse, "name")) style.name = attr(tse, "name");
527
- if (attr(tse, "pivot") === "1") style.pivot = true;
528
- const elements = [];
529
- for (const tsee of tse.elements ?? []) {
530
- if (tsee.name !== "tableStyleElement") continue;
531
- const elOpts = {};
532
- if (attr(tsee, "type")) elOpts.type = attr(tsee, "type");
533
- const dxfId = attrNum(tsee, "dxfId");
534
- if (dxfId !== void 0) elOpts.dxfId = dxfId;
535
- if (attr(tsee, "button") === "1") elOpts.button = true;
536
- elements.push(elOpts);
537
- }
538
- if (elements.length > 0) style.elements = elements;
539
- customStyles.push(style);
540
- }
541
- if (customStyles.length > 0) ts.tableStyles = customStyles;
542
- result.tableStylesInfo = ts;
543
- }
544
- const colorsEl = findChild(el, "colors");
545
- if (colorsEl) {
546
- const colors = {};
547
- const icEl = findChild(colorsEl, "indexedColors");
548
- if (icEl) {
549
- const indexed = [];
550
- for (const rgb of icEl.elements ?? []) if (rgb.name === "rgbColor" && attr(rgb, "rgb")) indexed.push({ rgb: attr(rgb, "rgb") });
551
- colors.indexedColors = indexed;
552
- }
553
- const mruEl = findChild(colorsEl, "mruColors");
554
- if (mruEl) {
555
- const mru = [];
556
- for (const c of mruEl.elements ?? []) if (c.name === "color") {
557
- const rgb = attr(c, "rgb");
558
- if (rgb) mru.push(rgb.length === 8 ? rgb.slice(2) : rgb);
559
- }
560
- colors.mruColors = mru;
561
- }
562
- result.colors = colors;
563
- }
564
- const extLstEl = findChild(el, "extLst");
565
- if (extLstEl) {
566
- const exts = [];
567
- for (const ext of extLstEl.elements ?? []) {
568
- if (ext.name !== "ext") continue;
569
- const uri = attr(ext, "uri");
570
- if (uri) {
571
- const content = (ext.elements ?? []).map((e) => stringify(e)).join("");
572
- exts.push({
573
- uri,
574
- content: content || void 0
575
- });
576
- }
577
- }
578
- result.styleExtensions = exts;
579
- }
580
- return result;
581
- }
582
- };
583
- function parseFont(el) {
584
- const result = {};
585
- for (const child of el.elements ?? []) switch (child.name) {
586
- case "b":
587
- result.bold = true;
588
- break;
589
- case "i":
590
- result.italic = true;
591
- break;
592
- case "u":
593
- result.underline = true;
594
- break;
595
- case "strike":
596
- result.strike = true;
597
- break;
598
- case "outline":
599
- result.outline = true;
600
- break;
601
- case "shadow":
602
- result.shadow = true;
603
- break;
604
- case "condense":
605
- result.condense = true;
606
- break;
607
- case "extend":
608
- result.extend = true;
609
- break;
610
- case "sz":
611
- result.size = attrNum(child, "val");
612
- break;
613
- case "color":
614
- result.color = parseColorHex(child);
615
- break;
616
- case "name":
617
- result.font = attr(child, "val") ?? void 0;
618
- break;
619
- case "charset":
620
- result.charset = attrNum(child, "val");
621
- break;
622
- case "family":
623
- result.family = attrNum(child, "val");
624
- break;
625
- case "vertAlign":
626
- result.vertAlign = attr(child, "val") ?? void 0;
627
- break;
628
- case "scheme":
629
- result.scheme = attr(child, "val") ?? void 0;
630
- break;
631
- }
632
- return result;
633
- }
634
- function parseFill(el) {
635
- const patternFill = findChild(el, "patternFill");
636
- if (patternFill) {
637
- const result = {};
638
- const patternType = attr(patternFill, "patternType");
639
- if (patternType) result.patternType = patternType;
640
- const fg = findChild(patternFill, "fgColor");
641
- if (fg) result.color = parseColorHex(fg);
642
- const bg = findChild(patternFill, "bgColor");
643
- if (bg) result.bgColor = parseColorHex(bg);
644
- const indexed = fg ? attrNum(fg, "indexed") : void 0;
645
- if (indexed !== void 0) result.colorIndexed = indexed;
646
- return result;
647
- }
648
- const gradientFill = findChild(el, "gradientFill");
649
- if (gradientFill) {
650
- const result = { type: "gradient" };
651
- const gType = attr(gradientFill, "type");
652
- if (gType) result.gradientType = gType;
653
- const degree = attrNum(gradientFill, "degree");
654
- if (degree !== void 0) result.gradientDegree = degree;
655
- const left = attrNum(gradientFill, "left");
656
- if (left !== void 0) result.gradientLeft = left;
657
- const right = attrNum(gradientFill, "right");
658
- if (right !== void 0) result.gradientRight = right;
659
- const top = attrNum(gradientFill, "top");
660
- if (top !== void 0) result.gradientTop = top;
661
- const bottom = attrNum(gradientFill, "bottom");
662
- if (bottom !== void 0) result.gradientBottom = bottom;
663
- const stops = [];
664
- for (const s of gradientFill.elements ?? []) {
665
- if (s.name !== "stop") continue;
666
- const pos = attrNum(s, "position");
667
- const color = findChild(s, "color");
668
- if (pos !== void 0 && color) stops.push({
669
- position: pos,
670
- color: parseColorHex(color) ?? ""
671
- });
672
- }
673
- if (stops.length > 0) result.stops = stops;
674
- return result;
675
- }
676
- return {};
677
- }
678
- function parseBorder(el) {
679
- const result = {};
680
- if (attr(el, "diagonalUp") === "1") result.diagonalUp = true;
681
- if (attr(el, "diagonalDown") === "1") result.diagonalDown = true;
682
- for (const side of [
683
- "left",
684
- "right",
685
- "top",
686
- "bottom",
687
- "diagonal",
688
- "start",
689
- "end",
690
- "vertical",
691
- "horizontal"
692
- ]) {
693
- const sideEl = findChild(el, side);
694
- if (sideEl) {
695
- const opts = {};
696
- const style = attr(sideEl, "style");
697
- if (style) opts.style = style;
698
- const color = findChild(sideEl, "color");
699
- if (color) opts.color = parseColorHex(color);
700
- if (Object.keys(opts).length > 0) result[side] = opts;
701
- }
702
- }
703
- return result;
704
- }
705
- function parseAlignment(el) {
706
- const result = {};
707
- const h = attr(el, "horizontal");
708
- if (h) result.horizontal = h;
709
- const v = attr(el, "vertical");
710
- if (v) result.vertical = v;
711
- if (attr(el, "wrapText") === "1") result.wrapText = true;
712
- const rotation = attrNum(el, "textRotation");
713
- if (rotation !== void 0) result.textRotation = rotation;
714
- const indent = attrNum(el, "indent");
715
- if (indent !== void 0) result.indent = indent;
716
- const relativeIndent = attrNum(el, "relativeIndent");
717
- if (relativeIndent !== void 0) result.relativeIndent = relativeIndent;
718
- if (attr(el, "justifyLastLine") === "1") result.justifyLastLine = true;
719
- if (attr(el, "shrinkToFit") === "1") result.shrinkToFit = true;
720
- const readingOrder = attrNum(el, "readingOrder");
721
- if (readingOrder !== void 0) result.readingOrder = readingOrder;
722
- return result;
723
- }
724
- function parseProtection(el) {
725
- const result = {};
726
- const locked = attr(el, "locked");
727
- if (locked !== void 0) result.locked = locked !== "0";
728
- const hidden = attr(el, "hidden");
729
- if (hidden !== void 0) result.hidden = hidden !== "0";
730
- return result;
731
- }
732
- function parseColorHex(el) {
733
- const rgb = attr(el, "rgb");
734
- if (rgb) return rgb.length === 8 ? rgb.slice(2) : rgb;
735
- }
736
- //#endregion
737
- //#region src/parts/calc-chain.ts
738
- const calcChainDesc = {
739
- kind: "custom",
740
- stringify(opts, _ctx) {
741
- const parts = ["<calcChain xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">"];
742
- for (const cell of opts.cells) {
743
- const cellAttrs = {
744
- r: cell.reference,
745
- i: cell.sheetIndex
746
- };
747
- if (cell.array) cellAttrs.a = true;
748
- parts.push(`<c${attrs(cellAttrs)}/>`);
749
- }
750
- parts.push("</calcChain>");
751
- return parts.join("");
752
- },
753
- parse(el, _ctx) {
754
- const result = {};
755
- const cells = [];
756
- for (const child of el.elements ?? []) {
757
- if (child.name !== "c") continue;
758
- const r = child.attributes?.["r"];
759
- const i = child.attributes?.["i"];
760
- if (r && i) {
761
- const cell = {
762
- reference: String(r),
763
- sheetIndex: Number(i)
764
- };
765
- if (child.attributes?.["a"]) cell.array = true;
766
- cells.push(cell);
767
- }
768
- }
769
- result.cells = cells;
770
- return result;
771
- }
772
- };
773
- //#endregion
774
- //#region src/parts/chartsheet.ts
775
- const chartsheetDesc = {
776
- kind: "custom",
777
- stringify(opts, _ctx) {
778
- const p = ["<chartsheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"];
779
- if (opts.tabColor || opts.published) {
780
- const prAttrs = [];
781
- if (opts.tabColor) prAttrs.push(`<tabColor${attrs({ rgb: opts.tabColor })}/>`);
782
- const spAttr = opts.published ? " published=\"1\"" : "";
783
- p.push(`<sheetPr${spAttr}>${prAttrs.join("")}</sheetPr>`);
784
- }
785
- const svAttrs = ["workbookViewId=\"0\""];
786
- if (opts.zoomToFit) svAttrs.push("zoomToFit=\"1\"");
787
- p.push(`<sheetViews><sheetView ${svAttrs.join(" ")}/></sheetViews>`);
788
- if (opts.sheetProtection) {
789
- const sp = opts.sheetProtection;
790
- const spAttrs = [];
791
- if (sp.content) spAttrs.push(` content="1"`);
792
- if (sp.objects) spAttrs.push(` objects="1"`);
793
- if (spAttrs.length > 0) p.push(`<sheetProtection${spAttrs.join("")}/>`);
794
- }
795
- if (opts.pageMargins) {
796
- const pm = opts.pageMargins;
797
- p.push(`<pageMargins${attrs({
798
- left: convertToInch(pm.left ?? .7),
799
- right: convertToInch(pm.right ?? .7),
800
- top: convertToInch(pm.top ?? .75),
801
- bottom: convertToInch(pm.bottom ?? .75),
802
- header: convertToInch(pm.header ?? .3),
803
- footer: convertToInch(pm.footer ?? .3)
804
- })}/>`);
805
- }
806
- if (opts.pageSetup) {
807
- const ps = opts.pageSetup;
808
- p.push(`<pageSetup${attrs({
809
- paperSize: ps.paperSize,
810
- orientation: ps.orientation,
811
- horizontalDpi: ps.horizontalDpi,
812
- verticalDpi: ps.verticalDpi,
813
- copies: ps.copies
814
- })}/>`);
815
- }
816
- if (opts.headerFooter) {
817
- const hf = opts.headerFooter;
818
- const hfParts = [];
819
- if (hf.differentFirst) hfParts.push(` differentFirst="1"`);
820
- if (hf.differentOddEven) hfParts.push(` differentOddEven="1"`);
821
- const hfContent = [];
822
- if (hf.oddHeader) hfContent.push(`<oddHeader>${escapeXml(hf.oddHeader)}</oddHeader>`);
823
- if (hf.oddFooter) hfContent.push(`<oddFooter>${escapeXml(hf.oddFooter)}</oddFooter>`);
824
- p.push(`<headerFooter${hfParts.join("")}>${hfContent.join("")}</headerFooter>`);
825
- }
826
- p.push(`<drawing r:id="${escapeXml(opts.drawingRId)}"/>`);
827
- p.push("</chartsheet>");
828
- return p.join("");
829
- },
830
- parse(el, _ctx) {
831
- const result = {};
832
- const sheetPr = findChild(el, "sheetPr");
833
- if (sheetPr) {
834
- if (sheetPr.attributes?.["published"] === "1") result.published = true;
835
- const tabColor = findChild(sheetPr, "tabColor");
836
- if (tabColor?.attributes?.["rgb"]) result.tabColor = String(tabColor.attributes["rgb"]);
837
- }
838
- const sheetViews = findChild(el, "sheetViews");
839
- if (sheetViews) {
840
- if (findChild(sheetViews, "sheetView")?.attributes?.["zoomToFit"] === "1") result.zoomToFit = true;
841
- }
842
- return result;
843
- }
844
- };
845
- //#endregion
846
- //#region src/parts/drawing.ts
847
- /**
848
- * XLSX Drawing — image and chart anchor types and descriptor.
849
- *
850
- * Generates xl/drawings/drawing{n}.xml using the spreadsheetDrawing
851
- * namespace for anchoring images and charts to worksheet cells.
852
- *
853
- * @module
854
- */
855
- /** How a drawing is anchored to the worksheet (xdr:*Anchor element). */
856
- const ANCHOR_TYPES = {
857
- twoCell: "twoCell",
858
- oneCell: "oneCell",
859
- absolute: "absolute"
860
- };
861
- /** editAs behavior for twoCellAnchor (ST_EditAs). */
862
- const EDIT_AS_TYPES = {
863
- twoCell: "twoCell",
864
- oneCell: "oneCell",
865
- absolute: "absolute"
866
- };
867
- const XDR_NS = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing";
868
- const A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main";
869
- const R_NS$1 = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
870
- const C_URI = "http://schemas.openxmlformats.org/drawingml/2006/chart";
871
- const DEFAULT_EXTENT_CX = 4e5;
872
- const DEFAULT_EXTENT_CY = 3e5;
873
- const drawingDesc = {
874
- kind: "custom",
875
- stringify(opts, _ctx) {
876
- const images = opts.images ?? [];
877
- const charts = opts.charts ?? [];
878
- if (images.length === 0 && charts.length === 0) return void 0;
879
- const p = [`<wsDr xmlns="${XDR_NS}" xmlns:a="${A_NS}" xmlns:r="${R_NS$1}">`];
880
- let id = 1;
881
- for (const img of images) {
882
- p.push(stringifyImage(img, id));
883
- id++;
884
- }
885
- for (const chart of charts) {
886
- p.push(stringifyChart(chart, id));
887
- id++;
888
- }
889
- p.push("</wsDr>");
890
- return p.join("");
891
- },
892
- parse(el, _ctx) {
893
- const result = {};
894
- const images = [];
895
- const charts = [];
896
- for (const anchor of el.elements ?? []) {
897
- const name = anchor.name;
898
- if (name !== "twoCellAnchor" && name !== "oneCellAnchor" && name !== "absoluteAnchor") continue;
899
- const pic = findChild(anchor, "pic");
900
- if (pic) {
901
- images.push(parseImageAnchor(anchor, pic, name));
902
- continue;
903
- }
904
- const graphicFrame = findChild(anchor, "graphicFrame");
905
- if (graphicFrame) {
906
- const chart = parseChartAnchor(anchor, graphicFrame);
907
- if (chart) charts.push(chart);
908
- }
909
- }
910
- if (images.length > 0) result.images = images;
911
- if (charts.length > 0) result.charts = charts;
912
- return result;
913
- }
914
- };
915
- /** Marker cell (0-based col/row + EMU offsets). */
916
- function markerXml(col, colOff, row, rowOff) {
917
- return `<col>${col - 1}</col><colOff>${convertToEmu(colOff)}</colOff><row>${row - 1}</row><rowOff>${convertToEmu(rowOff)}</rowOff>`;
918
- }
919
- function clientDataXml(img) {
920
- return `<clientData fLocksWithSheet="${img.locksWithSheet !== false ? 1 : 0}" fPrintsWithSheet="${img.printsWithSheet !== false ? 1 : 0}"/>`;
921
- }
922
- function picXml(rId, id, cx, cy) {
923
- return `<pic><nvPicPr><cNvPr id="${id}" name="Picture ${id}"/><cNvPicPr preferRelativeResize="1"/></nvPicPr><blipFill><a:blip r:embed="${rId}"/><a:stretch><a:fillRect/></a:stretch></blipFill><spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></spPr></pic>`;
924
- }
925
- function stringifyImage(img, id) {
926
- const anchorType = img.anchorType ?? ANCHOR_TYPES.twoCell;
927
- const cx = convertToEmu(img.extentCx ?? DEFAULT_EXTENT_CX);
928
- const cy = convertToEmu(img.extentCy ?? DEFAULT_EXTENT_CY);
929
- const pic = picXml(img.rId, id, cx, cy);
930
- const clientData = clientDataXml(img);
931
- if (anchorType === ANCHOR_TYPES.absolute) return `<absoluteAnchor><pos x="${convertToEmu(img.absoluteX ?? 0)}" y="${convertToEmu(img.absoluteY ?? 0)}"/><ext cx="${cx}" cy="${cy}"/>${pic}${clientData}</absoluteAnchor>`;
932
- const from = markerXml(img.col, img.colOffset ?? 0, img.row, img.rowOffset ?? 0);
933
- if (anchorType === ANCHOR_TYPES.oneCell) return `<oneCellAnchor><from>${from}</from><ext cx="${cx}" cy="${cy}"/>${pic}${clientData}</oneCellAnchor>`;
934
- return `<twoCellAnchor editAs="${img.editAs ?? EDIT_AS_TYPES.oneCell}"><from>${from}</from><to>${markerXml(img.toCol ?? img.col + 1, img.toColOffset ?? 0, img.toRow ?? img.row + 1, img.toRowOffset ?? 0)}</to>${pic}${clientData}</twoCellAnchor>`;
935
- }
936
- function stringifyChart(chart, id) {
937
- const from = markerXml(chart.col, chart.colOffset ?? 0, chart.row, chart.rowOffset ?? 0);
938
- const to = markerXml(chart.col + 9, 0, chart.row + 16, 0);
939
- const clientData = clientDataXml(chart);
940
- return `<twoCellAnchor editAs="oneCell"><from>${from}</from><to>${to}</to><graphicFrame><nvGraphicFramePr><cNvPr id="${id}" name="Chart ${id}"/><cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></cNvGraphicFramePr></nvGraphicFramePr><xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xfrm><a:graphic><a:graphicData uri="${C_URI}"><c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:r="${R_NS$1}" r:id="${chart.rId}"/></a:graphicData></a:graphic></graphicFrame>${clientData}</twoCellAnchor>`;
941
- }
942
- function readNumChild(el, tag) {
943
- const child = findChild(el, tag);
944
- if (!child?.elements?.length) return 0;
945
- const n = Number(child.elements[0]?.text ?? "");
946
- return Number.isNaN(n) ? 0 : n;
947
- }
948
- function readMarker(el) {
949
- return {
950
- col: readNumChild(el, "col") + 1,
951
- colOffset: readNumChild(el, "colOff") || void 0,
952
- row: readNumChild(el, "row") + 1,
953
- rowOffset: readNumChild(el, "rowOff") || void 0
954
- };
955
- }
956
- function readPicRId(pic) {
957
- return findChild(findChild(pic, "blipFill") ?? pic, "a:blip")?.attributes?.["r:embed"];
958
- }
959
- /** Picture extent from pic/spPr/a:xfrm/a:ext (actual image size in EMU). */
960
- function readPicExtent(pic) {
961
- const spPr = findChild(pic, "spPr");
962
- const xfrm = spPr ? findChild(spPr, "a:xfrm") : void 0;
963
- const ext = xfrm ? findChild(xfrm, "a:ext") : void 0;
964
- if (!ext?.attributes) return {};
965
- const cx = Number(ext.attributes["cx"]);
966
- const cy = Number(ext.attributes["cy"]);
967
- return {
968
- cx: Number.isNaN(cx) ? void 0 : cx,
969
- cy: Number.isNaN(cy) ? void 0 : cy
970
- };
971
- }
972
- function parseImageAnchor(anchor, pic, name) {
973
- const result = {
974
- col: 1,
975
- row: 1,
976
- rId: readPicRId(pic) ?? ""
977
- };
978
- const ext = readPicExtent(pic);
979
- if (ext.cx !== void 0) result.extentCx = ext.cx;
980
- if (ext.cy !== void 0) result.extentCy = ext.cy;
981
- const clientData = findChild(anchor, "clientData");
982
- if (clientData?.attributes) {
983
- if (clientData.attributes["fLocksWithSheet"] !== void 0) result.locksWithSheet = clientData.attributes["fLocksWithSheet"] !== "0";
984
- if (clientData.attributes["fPrintsWithSheet"] !== void 0) result.printsWithSheet = clientData.attributes["fPrintsWithSheet"] !== "0";
985
- }
986
- if (name === "absoluteAnchor") {
987
- result.anchorType = ANCHOR_TYPES.absolute;
988
- const pos = findChild(anchor, "pos");
989
- if (pos?.attributes) {
990
- const x = Number(pos.attributes["x"]);
991
- const y = Number(pos.attributes["y"]);
992
- if (!Number.isNaN(x)) result.absoluteX = x;
993
- if (!Number.isNaN(y)) result.absoluteY = y;
994
- }
995
- return result;
996
- }
997
- const from = findChild(anchor, "from");
998
- if (from) {
999
- const m = readMarker(from);
1000
- result.col = m.col;
1001
- result.row = m.row;
1002
- if (m.colOffset !== void 0) result.colOffset = m.colOffset;
1003
- if (m.rowOffset !== void 0) result.rowOffset = m.rowOffset;
1004
- }
1005
- if (name === "oneCellAnchor") {
1006
- result.anchorType = ANCHOR_TYPES.oneCell;
1007
- return result;
1008
- }
1009
- result.anchorType = ANCHOR_TYPES.twoCell;
1010
- const to = findChild(anchor, "to");
1011
- if (to) {
1012
- const m = readMarker(to);
1013
- result.toCol = m.col;
1014
- result.toRow = m.row;
1015
- if (m.colOffset !== void 0) result.toColOffset = m.colOffset;
1016
- if (m.rowOffset !== void 0) result.toRowOffset = m.rowOffset;
1017
- }
1018
- const editAs = anchor.attributes?.["editAs"];
1019
- if (editAs) result.editAs = editAs;
1020
- return result;
1021
- }
1022
- function parseChartAnchor(anchor, graphicFrame) {
1023
- const graphicData = findChild(findChild(graphicFrame, "a:graphic") ?? graphicFrame, "a:graphicData");
1024
- const rId = (graphicData ? findChild(graphicData, "c:chart") : void 0)?.attributes?.["r:id"];
1025
- if (!rId) return void 0;
1026
- const result = {
1027
- col: 1,
1028
- row: 1,
1029
- rId
1030
- };
1031
- const from = findChild(anchor, "from");
1032
- if (from) {
1033
- const m = readMarker(from);
1034
- result.col = m.col;
1035
- result.row = m.row;
1036
- if (m.colOffset !== void 0) result.colOffset = m.colOffset;
1037
- if (m.rowOffset !== void 0) result.rowOffset = m.rowOffset;
1038
- }
1039
- const clientData = findChild(anchor, "clientData");
1040
- if (clientData?.attributes) {
1041
- if (clientData.attributes["fLocksWithSheet"] !== void 0) result.locksWithSheet = clientData.attributes["fLocksWithSheet"] !== "0";
1042
- if (clientData.attributes["fPrintsWithSheet"] !== void 0) result.printsWithSheet = clientData.attributes["fPrintsWithSheet"] !== "0";
1043
- }
1044
- return result;
1045
- }
1046
- //#endregion
1047
- //#region src/parts/external-link.ts
1048
- const externalLinkDesc = {
1049
- kind: "custom",
1050
- stringify(opts, _ctx) {
1051
- const p = ["<externalLink xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"];
1052
- if (opts.externalBook) {
1053
- const book = opts.externalBook;
1054
- const bookParts = [];
1055
- if (book.sheetNames && book.sheetNames.length > 0) {
1056
- bookParts.push("<sheetNames>");
1057
- for (const name of book.sheetNames) bookParts.push(`<sheetName val="${escapeXml(name)}"/>`);
1058
- bookParts.push("</sheetNames>");
1059
- }
1060
- if (book.definedNames && book.definedNames.length > 0) {
1061
- bookParts.push("<definedNames>");
1062
- for (const dn of book.definedNames) {
1063
- const dnAttrs = { name: dn.name };
1064
- if (dn.refersTo !== void 0) dnAttrs.refersTo = dn.refersTo;
1065
- if (dn.sheetId !== void 0) dnAttrs.sheetId = dn.sheetId;
1066
- if (dn.publishToServer) dnAttrs.publishToServer = 1;
1067
- if (dn.vbProcedure) dnAttrs.vbProcedure = 1;
1068
- if (dn.workbookParameter) dnAttrs.workbookParameter = 1;
1069
- if (dn.xlm) dnAttrs.xlm = 1;
1070
- bookParts.push(`<definedName${attrs(dnAttrs)}/>`);
1071
- }
1072
- bookParts.push("</definedNames>");
1073
- }
1074
- if (book.sheetDataSet && book.sheetDataSet.length > 0) {
1075
- bookParts.push("<sheetDataSet>");
1076
- for (const sd of book.sheetDataSet) {
1077
- const sdAttrs = { sheetId: sd.sheetId };
1078
- if (sd.refreshError) sdAttrs.refreshError = 1;
1079
- bookParts.push(`<sheetData${attrs(sdAttrs)}>`);
1080
- if (sd.rows) for (const row of sd.rows) {
1081
- bookParts.push(`<row r="${row.rowNumber}">`);
1082
- if (row.cells) for (const cell of row.cells) {
1083
- const cellAttrs = { r: cell.reference };
1084
- if (cell.type !== void 0) cellAttrs.t = cell.type;
1085
- if (cell.value !== void 0) bookParts.push(`<cell${attrs(cellAttrs)}><v>${escapeXml(cell.value)}</v></cell>`);
1086
- else bookParts.push(`<cell${attrs(cellAttrs)}/>`);
1087
- }
1088
- bookParts.push("</row>");
1089
- }
1090
- bookParts.push("</sheetData>");
1091
- }
1092
- bookParts.push("</sheetDataSet>");
1093
- }
1094
- const ridAttr = opts.bookRId ? ` r:id="${opts.bookRId}"` : "";
1095
- p.push(`<externalBook${ridAttr}${bookParts.length > 0 ? `>${bookParts.join("")}</externalBook>` : "/>"}`);
1096
- }
1097
- if (opts.oleLink) {
1098
- const oleRId = opts.oleRId ? ` r:id="${escapeXml(opts.oleRId)}"` : "";
1099
- const oleChildren = [];
1100
- if (opts.oleLink.oleItems && opts.oleLink.oleItems.length > 0) {
1101
- const itemParts = [`<oleItems>`];
1102
- for (const item of opts.oleLink.oleItems) {
1103
- const itemAttrs = [`name="${escapeXml(item.name)}"`];
1104
- if (item.advise) itemAttrs.push("advise=\"1\"");
1105
- if (item.prefer) itemAttrs.push("prefer=\"1\"");
1106
- itemParts.push(`<oleItem ${itemAttrs.join(" ")}/>`);
1107
- }
1108
- itemParts.push("</oleItems>");
1109
- oleChildren.push(itemParts.join(""));
1110
- }
1111
- if (oleChildren.length > 0) p.push(`<oleLink${oleRId}>${oleChildren.join("")}</oleLink>`);
1112
- else p.push(`<oleLink${oleRId}/>`);
1113
- }
1114
- p.push("</externalLink>");
1115
- return p.join("");
1116
- },
1117
- parse(el, _ctx) {
1118
- const result = {};
1119
- const bookEl = findChild(el, "externalBook");
1120
- if (bookEl) {
1121
- const book = {};
1122
- if (bookEl.attributes?.["r:id"]) result.bookRId = String(bookEl.attributes["r:id"]);
1123
- const sheetNamesEl = findChild(bookEl, "sheetNames");
1124
- if (sheetNamesEl) {
1125
- const names = [];
1126
- for (const child of sheetNamesEl.elements ?? []) if (child.name === "sheetName" && child.attributes?.["val"]) names.push(String(child.attributes["val"]));
1127
- if (names.length > 0) book.sheetNames = names;
1128
- }
1129
- const definedNamesEl = findChild(bookEl, "definedNames");
1130
- if (definedNamesEl) {
1131
- const dns = [];
1132
- for (const child of definedNamesEl.elements ?? []) {
1133
- if (child.name !== "definedName") continue;
1134
- const dn = { name: String(child.attributes?.["name"] ?? "") };
1135
- if (child.attributes?.["refersTo"]) dn.refersTo = String(child.attributes["refersTo"]);
1136
- if (child.attributes?.["sheetId"] !== void 0) dn.sheetId = Number(child.attributes["sheetId"]);
1137
- if (child.attributes?.["publishToServer"]) dn.publishToServer = true;
1138
- if (child.attributes?.["vbProcedure"]) dn.vbProcedure = true;
1139
- if (child.attributes?.["workbookParameter"]) dn.workbookParameter = true;
1140
- if (child.attributes?.["xlm"]) dn.xlm = true;
1141
- dns.push(dn);
1142
- }
1143
- if (dns.length > 0) book.definedNames = dns;
1144
- }
1145
- const sheetDataSetEl = findChild(bookEl, "sheetDataSet");
1146
- if (sheetDataSetEl) {
1147
- const sds = [];
1148
- for (const sdChild of sheetDataSetEl.elements ?? []) {
1149
- if (sdChild.name !== "sheetData") continue;
1150
- const sd = { sheetId: Number(sdChild.attributes?.["sheetId"] ?? 0) };
1151
- if (sdChild.attributes?.["refreshError"]) sd.refreshError = true;
1152
- const rows = [];
1153
- for (const rowChild of sdChild.elements ?? []) {
1154
- if (rowChild.name !== "row") continue;
1155
- const row = { rowNumber: Number(rowChild.attributes?.["r"] ?? 0) };
1156
- const cells = [];
1157
- for (const cellChild of rowChild.elements ?? []) {
1158
- if (cellChild.name !== "cell") continue;
1159
- const cell = { reference: String(cellChild.attributes?.["r"] ?? "") };
1160
- if (cellChild.attributes?.["t"]) cell.type = String(cellChild.attributes["t"]);
1161
- const vEl = findChild(cellChild, "v");
1162
- if (vEl && vEl.elements?.[0]?.text !== void 0) cell.value = String(vEl.elements[0].text);
1163
- cells.push(cell);
1164
- }
1165
- if (cells.length > 0) row.cells = cells;
1166
- rows.push(row);
1167
- }
1168
- if (rows.length > 0) sd.rows = rows;
1169
- sds.push(sd);
1170
- }
1171
- if (sds.length > 0) book.sheetDataSet = sds;
1172
- }
1173
- result.externalBook = book;
1174
- }
1175
- const oleEl = findChild(el, "oleLink");
1176
- if (oleEl) {
1177
- const ole = {};
1178
- if (oleEl.attributes?.["r:id"]) result.oleRId = String(oleEl.attributes["r:id"]);
1179
- const oleItemsEl = findChild(oleEl, "oleItems");
1180
- if (oleItemsEl) {
1181
- const items = [];
1182
- for (const child of oleItemsEl.elements ?? []) {
1183
- if (child.name !== "oleItem") continue;
1184
- const item = { name: String(child.attributes?.["name"] ?? "") };
1185
- if (child.attributes?.["advise"]) item.advise = true;
1186
- if (child.attributes?.["prefer"]) item.prefer = true;
1187
- items.push(item);
1188
- }
1189
- if (items.length > 0) ole.oleItems = items;
1190
- }
1191
- result.oleLink = ole;
1192
- }
1193
- return result;
1194
- }
1195
- };
1196
- //#endregion
1197
- //#region src/parts/pivot/pivot-utils.ts
1198
- /** Pivot filter type (ST_PivotFilterType) */
1199
- const PivotFilterType = {
1200
- UNKNOWN: "unknown",
1201
- COUNT: "count",
1202
- PERCENT: "percent",
1203
- SUM: "sum",
1204
- CAPTION_EQUAL: "captionEqual",
1205
- CAPTION_NOT_EQUAL: "captionNotEqual",
1206
- CAPTION_BEGINS_WITH: "captionBeginsWith",
1207
- CAPTION_NOT_BEGINS_WITH: "captionNotBeginsWith",
1208
- CAPTION_ENDS_WITH: "captionEndsWith",
1209
- CAPTION_NOT_ENDS_WITH: "captionNotEndsWith",
1210
- CAPTION_CONTAINS: "captionContains",
1211
- CAPTION_NOT_CONTAINS: "captionNotContains",
1212
- CAPTION_GREATER_THAN: "captionGreaterThan",
1213
- CAPTION_GREATER_THAN_OR_EQUAL: "captionGreaterThanOrEqual",
1214
- CAPTION_LESS_THAN: "captionLessThan",
1215
- CAPTION_LESS_THAN_OR_EQUAL: "captionLessThanOrEqual",
1216
- CAPTION_BETWEEN: "captionBetween",
1217
- CAPTION_NOT_BETWEEN: "captionNotBetween",
1218
- VALUE_EQUAL: "valueEqual",
1219
- VALUE_NOT_EQUAL: "valueNotEqual",
1220
- VALUE_GREATER_THAN: "valueGreaterThan",
1221
- VALUE_GREATER_THAN_OR_EQUAL: "valueGreaterThanOrEqual",
1222
- VALUE_LESS_THAN: "valueLessThan",
1223
- VALUE_LESS_THAN_OR_EQUAL: "valueLessThanOrEqual",
1224
- VALUE_BETWEEN: "valueBetween",
1225
- VALUE_NOT_BETWEEN: "valueNotBetween",
1226
- DATE_EQUAL: "dateEqual",
1227
- DATE_NOT_EQUAL: "dateNotEqual",
1228
- DATE_OLDER_THAN: "dateOlderThan",
1229
- DATE_OLDER_THAN_OR_EQUAL: "dateOlderThanOrEqual",
1230
- DATE_NEWER_THAN: "dateNewerThan",
1231
- DATE_NEWER_THAN_OR_EQUAL: "dateNewerThanOrEqual",
1232
- DATE_BETWEEN: "dateBetween",
1233
- DATE_NOT_BETWEEN: "dateNotBetween",
1234
- TOMORROW: "tomorrow",
1235
- TODAY: "today",
1236
- YESTERDAY: "yesterday",
1237
- NEXT_WEEK: "nextWeek",
1238
- THIS_WEEK: "thisWeek",
1239
- LAST_WEEK: "lastWeek",
1240
- NEXT_MONTH: "nextMonth",
1241
- THIS_MONTH: "thisMonth",
1242
- LAST_MONTH: "lastMonth",
1243
- NEXT_QUARTER: "nextQuarter",
1244
- THIS_QUARTER: "thisQuarter",
1245
- LAST_QUARTER: "lastQuarter",
1246
- NEXT_YEAR: "nextYear",
1247
- THIS_YEAR: "thisYear",
1248
- LAST_YEAR: "lastYear",
1249
- YEAR_TO_DATE: "yearToDate",
1250
- Q1: "Q1",
1251
- Q2: "Q2",
1252
- Q3: "Q3",
1253
- Q4: "Q4",
1254
- M1: "M1",
1255
- M2: "M2",
1256
- M3: "M3",
1257
- M4: "M4",
1258
- M5: "M5",
1259
- M6: "M6",
1260
- M7: "M7",
1261
- M8: "M8",
1262
- M9: "M9",
1263
- M10: "M10",
1264
- M11: "M11",
1265
- M12: "M12"
1266
- };
1267
- /**
1268
- * Extract unique values from source data for a given field index.
1269
- */
1270
- function collectUniqueValues(records, fieldIdx) {
1271
- const seen = /* @__PURE__ */ new Set();
1272
- const result = [];
1273
- for (const row of records) {
1274
- const val = row[fieldIdx];
1275
- const key = val instanceof Date ? val.toISOString() : String(val);
1276
- if (!seen.has(key)) {
1277
- seen.add(key);
1278
- result.push(val ?? null);
1279
- }
1280
- }
1281
- return result;
1282
- }
1283
- /**
1284
- * Check if a field is numeric (all non-empty values are numbers).
1285
- */
1286
- function isNumericField(records, fieldIdx) {
1287
- for (const row of records) {
1288
- const val = row[fieldIdx];
1289
- if (typeof val === "string" && val !== "") return false;
1290
- }
1291
- return true;
1292
- }
1293
- /**
1294
- * Aggregate values using the specified function.
1295
- */
1296
- function aggregate(values, func) {
1297
- if (values.length === 0) return 0;
1298
- switch (func) {
1299
- case "sum": return values.reduce((a, b) => a + b, 0);
1300
- case "count":
1301
- case "countNums": return values.length;
1302
- case "average": return values.reduce((a, b) => a + b, 0) / values.length;
1303
- case "max": return values.reduce((a, b) => Math.max(a, b));
1304
- case "min": return values.reduce((a, b) => Math.min(a, b));
1305
- case "product": return values.reduce((a, b) => a * b, 1);
1306
- case "var": return sampleVariance(values);
1307
- case "varp": return populationVariance(values);
1308
- case "stdDev": return Math.sqrt(sampleVariance(values));
1309
- case "stdDevp": return Math.sqrt(populationVariance(values));
1310
- default: return values.reduce((a, b) => a + b, 0);
1311
- }
1312
- }
1313
- function populationVariance(values) {
1314
- const mean = values.reduce((a, b) => a + b, 0) / values.length;
1315
- return values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / values.length;
1316
- }
1317
- function sampleVariance(values) {
1318
- if (values.length < 2) return 0;
1319
- const mean = values.reduce((a, b) => a + b, 0) / values.length;
1320
- return values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / (values.length - 1);
1321
- }
1322
- //#endregion
1323
- //#region src/parts/pivot-table.ts
1324
- const pivotTableDesc = {
1325
- kind: "custom",
1326
- stringify(opts, _ctx) {
1327
- return stringifyPivotTable(opts.options, opts.sourceData, opts.cacheId);
1328
- },
1329
- parse(el, _ctx) {
1330
- const result = {};
1331
- if (attr(el, "name")) result.name = attr(el, "name");
1332
- if (attr(el, "cacheId") !== void 0) result.cacheId = attrNum(el, "cacheId") ?? 0;
1333
- if (attr(el, "dataOnRows") === "1") result.dataOnRows = true;
1334
- if (attr(el, "showHeaders") === "0") result.showHeaders = false;
1335
- if (attr(el, "showEmptyRow") === "1") result.showEmptyRow = true;
1336
- if (attr(el, "showEmptyCol") === "1") result.showEmptyCol = true;
1337
- if (attr(el, "grandTotalCaption")) result.grandTotalCaption = attr(el, "grandTotalCaption");
1338
- if (attr(el, "errorCaption")) result.errorCaption = attr(el, "errorCaption");
1339
- if (attr(el, "showError") === "1") result.showError = true;
1340
- if (attr(el, "missingCaption")) result.missingCaption = attr(el, "missingCaption");
1341
- if (attr(el, "showMissing") === "0") result.showMissing = false;
1342
- if (attr(el, "pageStyle")) result.pageStyle = attr(el, "pageStyle");
1343
- if (attr(el, "pivotTableStyle")) result.pivotTableStyle = attr(el, "pivotTableStyle");
1344
- if (attr(el, "tag")) result.tag = attr(el, "tag");
1345
- if (attr(el, "showItems") === "0") result.showItems = false;
1346
- if (attr(el, "editData") === "1") result.editData = true;
1347
- if (attr(el, "disableFieldList") === "1") result.disableFieldList = true;
1348
- if (attr(el, "showCalcMbrs") === "0") result.showCalcMbrs = false;
1349
- if (attr(el, "visualTotals") === "1") result.visualTotals = true;
1350
- if (attr(el, "showMultipleLabel") === "0") result.showMultipleLabel = false;
1351
- if (attr(el, "showDataDropDown") === "0") result.showDataDropDown = false;
1352
- if (attr(el, "showDrill") === "0") result.showDrill = false;
1353
- if (attr(el, "printDrill") === "1") result.printDrill = true;
1354
- if (attr(el, "showMemberPropertyTips") === "1") result.showMemberPropertyTips = true;
1355
- if (attr(el, "showDataTips") === "0") result.showDataTips = false;
1356
- if (attr(el, "enableWizard") === "0") result.enableWizard = false;
1357
- if (attr(el, "enableDrill") === "0") result.enableDrill = false;
1358
- if (attr(el, "enableFieldProperties") === "0") result.enableFieldProperties = false;
1359
- const pageWrap = attrNum(el, "pageWrap");
1360
- if (pageWrap !== void 0) result.pageWrap = pageWrap;
1361
- if (attr(el, "pageOverThenDown") === "1") result.pageOverThenDown = true;
1362
- if (attr(el, "subtotalHiddenItems") === "1") result.subtotalHiddenItems = true;
1363
- if (attr(el, "fieldPrintTitles") === "1") result.fieldPrintTitles = true;
1364
- if (attr(el, "mergeItem") === "1") result.mergeItem = true;
1365
- if (attr(el, "showDropZones") === "0") result.showDropZones = false;
1366
- if (attr(el, "published") === "1") result.published = true;
1367
- if (attr(el, "gridDropZones") === "0") result.gridDropZones = false;
1368
- if (attr(el, "multipleFieldFilters") === "0") result.multipleFieldFilters = false;
1369
- if (attr(el, "rowHeaderCaption")) result.rowHeaderCaption = attr(el, "rowHeaderCaption");
1370
- if (attr(el, "colHeaderCaption")) result.colHeaderCaption = attr(el, "colHeaderCaption");
1371
- if (attr(el, "fieldListSortAscending") === "1") result.fieldListSortAscending = true;
1372
- if (attr(el, "mdxSubqueries") === "1") result.mdxSubqueries = true;
1373
- if (attr(el, "customListSort") === "0") result.customListSort = false;
1374
- if (attr(el, "asteriskTotals") === "1") result.asteriskTotals = true;
1375
- const dataPosition = attrNum(el, "dataPosition");
1376
- if (dataPosition !== void 0) result.dataPosition = dataPosition;
1377
- if (attr(el, "immersive") === "1") result.immersive = true;
1378
- if (attr(el, "vacatedStyle")) result.vacatedStyle = attr(el, "vacatedStyle");
1379
- if (attr(el, "dataCaption")) result.dataCaption = attr(el, "dataCaption");
1380
- const locEl = findChild(el, "location");
1381
- if (locEl) {
1382
- if (attr(locEl, "ref")) result.location = attr(locEl, "ref");
1383
- const rpc = attrNum(locEl, "rowPageCount");
1384
- if (rpc !== void 0) result.locationRowPageCount = rpc;
1385
- const cpc = attrNum(locEl, "colPageCount");
1386
- if (cpc !== void 0) result.locationColPageCount = cpc;
1387
- }
1388
- const pfEl = findChild(el, "pivotFields");
1389
- if (pfEl) {
1390
- const fields = [];
1391
- for (const fEl of pfEl.elements ?? []) {
1392
- if (fEl.name !== "pivotField") continue;
1393
- const field = {};
1394
- const axis = attr(fEl, "axis");
1395
- if (axis) field.axis = axis;
1396
- if (attr(fEl, "showAll") === "0") field.showAll = false;
1397
- else if (attr(fEl, "showAll") === "1") field.showAll = true;
1398
- if (attr(fEl, "dataField") === "1") field.dataField = true;
1399
- if (attr(fEl, "hierarchy")) field.hierarchy = attr(fEl, "hierarchy");
1400
- if (attr(fEl, "dragToRow") === "0") field.dragToRow = false;
1401
- if (attr(fEl, "dragToCol") === "0") field.dragToCol = false;
1402
- if (attr(fEl, "dragToPage") === "0") field.dragToPage = false;
1403
- if (attr(fEl, "dragToData") === "1") field.dragToData = true;
1404
- if (attr(fEl, "dragOff") === "0") field.dragOff = false;
1405
- if (attr(fEl, "showDropDowns") === "0") field.showDropDowns = false;
1406
- if (attr(fEl, "insertBlankRow") === "1") field.insertBlankRow = true;
1407
- if (attr(fEl, "showPropCell") === "1") field.showPropCell = true;
1408
- if (attr(fEl, "showPropTip") === "1") field.showPropTip = true;
1409
- if (attr(fEl, "showPropAsCaption") === "1") field.showPropAsCaption = true;
1410
- if (attr(fEl, "compact") === "0") field.compact = false;
1411
- if (attr(fEl, "outline") === "1") field.outline = true;
1412
- if (attr(fEl, "subtotalTop") === "0") field.subtotalTop = false;
1413
- if (attr(fEl, "includeNewItemsInFilter") === "1") field.includeNewItemsInFilter = true;
1414
- fields.push(field);
1415
- }
1416
- result.pivotFields = fields;
1417
- }
1418
- const dfEl = findChild(el, "dataFields");
1419
- if (dfEl) {
1420
- const dataFields = [];
1421
- for (const dEl of dfEl.elements ?? []) {
1422
- if (dEl.name !== "dataField") continue;
1423
- const df = {};
1424
- if (attr(dEl, "name")) df.name = attr(dEl, "name");
1425
- const fld = attrNum(dEl, "fld");
1426
- if (fld !== void 0) df.fld = fld;
1427
- if (attr(dEl, "subtotal")) df.subtotal = attr(dEl, "subtotal");
1428
- if (attr(dEl, "showDataAs")) df.showDataAs = attr(dEl, "showDataAs");
1429
- const baseField = attrNum(dEl, "baseField");
1430
- if (baseField !== void 0) df.baseField = baseField;
1431
- const baseItem = attrNum(dEl, "baseItem");
1432
- if (baseItem !== void 0) df.baseItem = baseItem;
1433
- if (attr(dEl, "numFmtId")) df.numFmtId = attr(dEl, "numFmtId");
1434
- dataFields.push(df);
1435
- }
1436
- result.dataFields = dataFields;
1437
- }
1438
- const rowFieldsEl = findChild(el, "rowFields");
1439
- if (rowFieldsEl) {
1440
- const rowFields = [];
1441
- for (const f of rowFieldsEl.elements ?? []) if (f.name === "field") {
1442
- const x = attrNum(f, "x");
1443
- if (x !== void 0) rowFields.push(x);
1444
- }
1445
- result.rowFields = rowFields;
1446
- }
1447
- const colFieldsEl = findChild(el, "colFields");
1448
- if (colFieldsEl) {
1449
- const colFields = [];
1450
- for (const f of colFieldsEl.elements ?? []) if (f.name === "field") {
1451
- const x = attrNum(f, "x");
1452
- if (x !== void 0) colFields.push(x);
1453
- }
1454
- result.colFields = colFields;
1455
- }
1456
- const pageFieldsEl = findChild(el, "pageFields");
1457
- if (pageFieldsEl) {
1458
- const pageFields = [];
1459
- for (const pf of pageFieldsEl.elements ?? []) {
1460
- if (pf.name !== "pageField") continue;
1461
- const pfResult = {};
1462
- const fld = attrNum(pf, "fld");
1463
- if (fld !== void 0) pfResult.fld = fld;
1464
- const hier = attrNum(pf, "hier");
1465
- if (hier !== void 0) pfResult.hier = hier;
1466
- if (attr(pf, "cap")) pfResult.cap = attr(pf, "cap");
1467
- pageFields.push(pfResult);
1468
- }
1469
- result.pageFields = pageFields;
1470
- }
1471
- const formatsEl = findChild(el, "formats");
1472
- if (formatsEl) {
1473
- const formats = [];
1474
- for (const fmtEl of formatsEl.elements ?? []) {
1475
- if (fmtEl.name !== "format") continue;
1476
- const fmt = {};
1477
- if (attr(fmtEl, "action")) fmt.action = attr(fmtEl, "action");
1478
- const dxfId = attrNum(fmtEl, "dxfId");
1479
- if (dxfId !== void 0) fmt.dxfId = dxfId;
1480
- const paEl = findChild(fmtEl, "pivotArea");
1481
- if (paEl) fmt.pivotArea = parsePivotArea(paEl);
1482
- formats.push(fmt);
1483
- }
1484
- result.formats = formats;
1485
- }
1486
- const chartFormatsEl = findChild(el, "chartFormats");
1487
- if (chartFormatsEl) {
1488
- const chartFormats = [];
1489
- for (const cfEl of chartFormatsEl.elements ?? []) {
1490
- if (cfEl.name !== "chartFormat") continue;
1491
- const cf = {};
1492
- const chart = attrNum(cfEl, "chart");
1493
- if (chart !== void 0) cf.chart = chart;
1494
- const format = attrNum(cfEl, "format");
1495
- if (format !== void 0) cf.format = format;
1496
- if (attr(cfEl, "series") === "1") cf.series = true;
1497
- const paEl = findChild(cfEl, "pivotArea");
1498
- if (paEl) cf.pivotArea = parsePivotArea(paEl);
1499
- chartFormats.push(cf);
1500
- }
1501
- result.chartFormats = chartFormats;
1502
- }
1503
- const hierarchiesEl = findChild(el, "pivotHierarchies");
1504
- if (hierarchiesEl) {
1505
- const hierarchies = [];
1506
- for (const hEl of hierarchiesEl.elements ?? []) {
1507
- if (hEl.name !== "pivotHierarchy") continue;
1508
- const h = {};
1509
- if (attr(hEl, "outline") === "1") h.outline = true;
1510
- if (attr(hEl, "multipleItemSelectionAllowed") === "1") h.multipleItemSelectionAllowed = true;
1511
- if (attr(hEl, "subtotalTop") === "1") h.subtotalTop = true;
1512
- if (attr(hEl, "showInFieldList") === "0") h.showInFieldList = false;
1513
- if (attr(hEl, "dragToRow") === "0") h.dragToRow = false;
1514
- if (attr(hEl, "dragToCol") === "0") h.dragToCol = false;
1515
- if (attr(hEl, "dragToPage") === "0") h.dragToPage = false;
1516
- if (attr(hEl, "dragToData") === "1") h.dragToData = true;
1517
- if (attr(hEl, "dragOff") === "0") h.dragOff = false;
1518
- if (attr(hEl, "includeNewItemsInFilter") === "1") h.includeNewItemsInFilter = true;
1519
- if (attr(hEl, "caption")) h.caption = attr(hEl, "caption");
1520
- hierarchies.push(h);
1521
- }
1522
- result.pivotHierarchies = hierarchies;
1523
- }
1524
- const filtersEl = findChild(el, "filters");
1525
- if (filtersEl) {
1526
- const filters = [];
1527
- for (const fEl of filtersEl.elements ?? []) {
1528
- if (fEl.name !== "filter") continue;
1529
- const f = {};
1530
- const fld = attrNum(fEl, "fld");
1531
- if (fld !== void 0) f.fld = fld;
1532
- if (attr(fEl, "type")) f.type = attr(fEl, "type");
1533
- const id = attrNum(fEl, "id");
1534
- if (id !== void 0) f.id = id;
1535
- const mpFld = attrNum(fEl, "mpFld");
1536
- if (mpFld !== void 0) f.mpFld = mpFld;
1537
- const evalOrder = attrNum(fEl, "evalOrder");
1538
- if (evalOrder !== void 0) f.evalOrder = evalOrder;
1539
- filters.push(f);
1540
- }
1541
- result.filters = filters;
1542
- }
1543
- const rhuEl = findChild(el, "rowHierarchiesUsage");
1544
- if (rhuEl) {
1545
- const usage = [];
1546
- for (const u of rhuEl.elements ?? []) if (u.name === "rowHierarchyUsage") usage.push({ hierarchyUsage: attrNum(u, "hierarchyUsage") ?? 0 });
1547
- result.rowHierarchiesUsage = usage;
1548
- }
1549
- const chuEl = findChild(el, "colHierarchiesUsage");
1550
- if (chuEl) {
1551
- const usage = [];
1552
- for (const u of chuEl.elements ?? []) if (u.name === "colHierarchyUsage") usage.push({ hierarchyUsage: attrNum(u, "hierarchyUsage") ?? 0 });
1553
- result.colHierarchiesUsage = usage;
1554
- }
1555
- const ciEl = findChild(el, "calculatedItems");
1556
- if (ciEl) {
1557
- const items = [];
1558
- for (const iEl of ciEl.elements ?? []) {
1559
- if (iEl.name !== "calculatedItem") continue;
1560
- const item = {};
1561
- const field = attrNum(iEl, "field");
1562
- if (field !== void 0) item.field = field;
1563
- const formulaEl = findChild(iEl, "formula");
1564
- if (formulaEl) item.formula = textOf(formulaEl);
1565
- const paEl = findChild(iEl, "pivotArea");
1566
- if (paEl) item.pivotArea = parsePivotArea(paEl);
1567
- items.push(item);
1568
- }
1569
- result.calculatedItems = items;
1570
- }
1571
- const cmEl = findChild(el, "calculatedMembers");
1572
- if (cmEl) {
1573
- const members = [];
1574
- for (const mEl of cmEl.elements ?? []) {
1575
- if (mEl.name !== "calculatedMember") continue;
1576
- const m = {};
1577
- if (attr(mEl, "name")) m.name = attr(mEl, "name");
1578
- const mdxEl = findChild(mEl, "mdx");
1579
- if (mdxEl) m.mdx = textOf(mdxEl) ?? "";
1580
- if (attr(mEl, "memberName")) m.memberName = attr(mEl, "memberName");
1581
- if (attr(mEl, "hierarchy")) m.hierarchy = attr(mEl, "hierarchy");
1582
- if (attr(mEl, "parent")) m.parent = attr(mEl, "parent");
1583
- const solveOrder = attrNum(mEl, "solveOrder");
1584
- if (solveOrder !== void 0) m.solveOrder = solveOrder;
1585
- if (attr(mEl, "set") === "1") m.set = true;
1586
- members.push(m);
1587
- }
1588
- result.calculatedMembers = members;
1589
- }
1590
- const styleInfoEl = findChild(el, "pivotTableStyleInfo");
1591
- if (styleInfoEl) {
1592
- const styleName = attr(styleInfoEl, "name");
1593
- if (styleName) result.style = styleName;
1594
- } else if (attr(el, "styleName")) result.style = attr(el, "styleName");
1595
- return result;
1596
- }
1597
- };
1598
- function stringifyPivotTable(o, sd, cacheId) {
1599
- const fields = sd.fieldNames;
1600
- const rowFieldNames = o.rows;
1601
- const colFieldNames = o.columns ?? [];
1602
- const dataFields = o.data;
1603
- const style = o.style ?? "PivotStyleLight16";
1604
- const location = o.location ?? "A3";
1605
- const name = o.name ?? "PivotTable1";
1606
- const rowFieldIndices = rowFieldNames.map((n) => fields.indexOf(n));
1607
- const colFieldIndices = colFieldNames.map((n) => fields.indexOf(n));
1608
- const dataFieldIndices = dataFields.map((df) => fields.indexOf(df.field));
1609
- const pageFieldIndices = (o.pages ?? []).map((n) => fields.indexOf(n));
1610
- const pivotFieldsXml = buildPivotFields(o, sd, rowFieldIndices, colFieldIndices, dataFieldIndices, pageFieldIndices);
1611
- const pageFieldsXml = buildPageFields(o, pageFieldIndices);
1612
- const rowFieldsXml = buildRowFields(rowFieldIndices);
1613
- const rowItemsXml = buildRowItems(sd, rowFieldIndices);
1614
- const colFieldsXml = buildColFields(colFieldIndices);
1615
- const colItemsXml = buildColItems(sd, colFieldIndices, dataFields);
1616
- const dataFieldsXml = buildDataFields(dataFields, dataFieldIndices);
1617
- const locationRef = computeLocationRef(sd, location, rowFieldIndices, colFieldIndices, dataFields);
1618
- const p = [];
1619
- const defAttrs = [
1620
- `name="${escapeXml(name)}"`,
1621
- `cacheId="${cacheId}"`,
1622
- "dataCaption=\"Values\"",
1623
- "updatedVersion=\"6\"",
1624
- "minRefreshableVersion=\"3\"",
1625
- "createdVersion=\"6\"",
1626
- "applyNumberFormats=\"0\"",
1627
- "applyBorderFormats=\"0\"",
1628
- "applyFontFormats=\"0\"",
1629
- "applyPatternFormats=\"0\"",
1630
- "applyAlignmentFormats=\"0\"",
1631
- "applyWidthHeightFormats=\"1\"",
1632
- "autoFormatId=\"0\"",
1633
- "useAutoFormatting=\"1\"",
1634
- "itemPrintTitles=\"1\"",
1635
- "indent=\"0\"",
1636
- "outline=\"1\"",
1637
- "outlineData=\"1\"",
1638
- "compact=\"1\"",
1639
- "compactData=\"1\"",
1640
- "rowGrandTotals=\"1\"",
1641
- "colGrandTotals=\"1\""
1642
- ];
1643
- if (o.dataOnRows) defAttrs.push("dataOnRows=\"1\"");
1644
- if (o.grandTotalCaption) defAttrs.push(`grandTotalCaption="${escapeXml(o.grandTotalCaption)}"`);
1645
- if (o.errorCaption) defAttrs.push(`errorCaption="${escapeXml(o.errorCaption)}"`);
1646
- if (o.showError) defAttrs.push("showError=\"1\"");
1647
- if (o.missingCaption) defAttrs.push(`missingCaption="${escapeXml(o.missingCaption)}"`);
1648
- if (o.showMissing === false) defAttrs.push("showMissing=\"0\"");
1649
- if (o.pageStyle) defAttrs.push(`pageStyle="${escapeXml(o.pageStyle)}"`);
1650
- if (o.pivotTableStyle) defAttrs.push(`pivotTableStyle="${escapeXml(o.pivotTableStyle)}"`);
1651
- if (o.tag) defAttrs.push(`tag="${escapeXml(o.tag)}"`);
1652
- if (o.showItems === false) defAttrs.push("showItems=\"0\"");
1653
- if (o.editData) defAttrs.push("editData=\"1\"");
1654
- if (o.disableFieldList) defAttrs.push("disableFieldList=\"1\"");
1655
- if (o.showCalcMbrs === false) defAttrs.push("showCalcMbrs=\"0\"");
1656
- if (o.visualTotals) defAttrs.push("visualTotals=\"1\"");
1657
- if (o.showMultipleLabel === false) defAttrs.push("showMultipleLabel=\"0\"");
1658
- if (o.showDataDropDown === false) defAttrs.push("showDataDropDown=\"0\"");
1659
- if (o.showDrill === false) defAttrs.push("showDrill=\"0\"");
1660
- if (o.printDrill) defAttrs.push("printDrill=\"1\"");
1661
- if (o.showMemberPropertyTips) defAttrs.push("showMemberPropertyTips=\"1\"");
1662
- if (o.showDataTips === false) defAttrs.push("showDataTips=\"0\"");
1663
- if (o.enableWizard === false) defAttrs.push("enableWizard=\"0\"");
1664
- if (o.enableDrill === false) defAttrs.push("enableDrill=\"0\"");
1665
- if (o.enableFieldProperties === false) defAttrs.push("enableFieldProperties=\"0\"");
1666
- if (o.pageWrap !== void 0) defAttrs.push(`pageWrap="${o.pageWrap}"`);
1667
- if (o.pageOverThenDown) defAttrs.push("pageOverThenDown=\"1\"");
1668
- if (o.subtotalHiddenItems) defAttrs.push("subtotalHiddenItems=\"1\"");
1669
- if (o.fieldPrintTitles) defAttrs.push("fieldPrintTitles=\"1\"");
1670
- if (o.mergeItem) defAttrs.push("mergeItem=\"1\"");
1671
- if (o.showDropZones === false) defAttrs.push("showDropZones=\"0\"");
1672
- if (o.showEmptyRow) defAttrs.push("showEmptyRow=\"1\"");
1673
- if (o.showEmptyCol) defAttrs.push("showEmptyCol=\"1\"");
1674
- if (o.showHeaders === false) defAttrs.push("showHeaders=\"0\"");
1675
- if (o.published) defAttrs.push("published=\"1\"");
1676
- if (o.gridDropZones === false) defAttrs.push("gridDropZones=\"0\"");
1677
- if (o.multipleFieldFilters === false) defAttrs.push("multipleFieldFilters=\"0\"");
1678
- if (o.rowHeaderCaption) defAttrs.push(`rowHeaderCaption="${escapeXml(o.rowHeaderCaption)}"`);
1679
- if (o.colHeaderCaption) defAttrs.push(`colHeaderCaption="${escapeXml(o.colHeaderCaption)}"`);
1680
- if (o.fieldListSortAscending) defAttrs.push("fieldListSortAscending=\"1\"");
1681
- if (o.mdxSubqueries) defAttrs.push("mdxSubqueries=\"1\"");
1682
- if (o.customListSort === false) defAttrs.push("customListSort=\"0\"");
1683
- if (o.asteriskTotals) defAttrs.push("asteriskTotals=\"1\"");
1684
- if (o.dataPosition !== void 0) defAttrs.push(`dataPosition="${o.dataPosition}"`);
1685
- if (o.immersive) defAttrs.push("immersive=\"1\"");
1686
- if (o.vacatedStyle) defAttrs.push(`vacatedStyle="${escapeXml(o.vacatedStyle)}"`);
1687
- p.push(`<pivotTableDefinition xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ${defAttrs.join(" ")}>`);
1688
- const locAttrs = [
1689
- `ref="${escapeXml(locationRef)}"`,
1690
- `firstHeaderRow="1"`,
1691
- `firstDataRow="${colFieldIndices.length + 1}"`,
1692
- `firstDataCol="${rowFieldIndices.length}"`
1693
- ];
1694
- if (o.locationColPageCount !== void 0) locAttrs.push(`colPageCount="${o.locationColPageCount}"`);
1695
- if (o.locationRowPageCount !== void 0) locAttrs.push(`rowPageCount="${o.locationRowPageCount}"`);
1696
- p.push(`<location ${locAttrs.join(" ")}/>`);
1697
- p.push(pivotFieldsXml);
1698
- p.push(rowFieldsXml);
1699
- p.push(rowItemsXml);
1700
- if (colFieldIndices.length > 0) p.push(colFieldsXml);
1701
- p.push(colItemsXml);
1702
- if (pageFieldIndices.length > 0) p.push(pageFieldsXml);
1703
- if (dataFields.length > 0) p.push(dataFieldsXml);
1704
- if (o.formats && o.formats.length > 0) {
1705
- const fmtParts = [`<formats count="${o.formats.length}">`];
1706
- for (const fmt of o.formats) {
1707
- const fmtAttrs = [];
1708
- if (fmt.action && fmt.action !== "formatting") fmtAttrs.push(`action="${fmt.action}"`);
1709
- if (fmt.dxfId !== void 0) fmtAttrs.push(`dxfId="${fmt.dxfId}"`);
1710
- fmtParts.push(`<format${fmtAttrs.length ? " " + fmtAttrs.join(" ") : ""}>${buildPivotAreaXml(fmt.pivotArea)}</format>`);
1711
- }
1712
- fmtParts.push("</formats>");
1713
- p.push(fmtParts.join(""));
1714
- }
1715
- if (o.chartFormats && o.chartFormats.length > 0) {
1716
- const cfParts = [`<chartFormats count="${o.chartFormats.length}">`];
1717
- for (const cf of o.chartFormats) {
1718
- const cfAttrs = [`chart="${cf.chart}"`, `format="${cf.format}"`];
1719
- if (cf.series) cfAttrs.push("series=\"1\"");
1720
- const areaXml = cf.pivotArea ? buildPivotAreaXml(cf.pivotArea) : "";
1721
- cfParts.push(`<chartFormat ${cfAttrs.join(" ")}>${areaXml}</chartFormat>`);
1722
- }
1723
- cfParts.push("</chartFormats>");
1724
- p.push(cfParts.join(""));
1725
- }
1726
- if (o.pivotHierarchies && o.pivotHierarchies.length > 0) p.push(buildPivotHierarchies(o.pivotHierarchies));
1727
- p.push(`<pivotTableStyleInfo name="${escapeXml(style)}" showRowHeaders="1" showColHeaders="1" showRowStripes="0" showColStripes="0" showLastColumn="1"/>`);
1728
- if (o.filters && o.filters.length > 0) {
1729
- const fParts = [`<filters count="${o.filters.length}">`];
1730
- for (const f of o.filters) {
1731
- const fAttrs = {
1732
- fld: f.fld,
1733
- type: f.type,
1734
- id: f.id
1735
- };
1736
- if (f.mpFld !== void 0) fAttrs.mpFld = f.mpFld;
1737
- if (f.evalOrder !== void 0) fAttrs.evalOrder = f.evalOrder;
1738
- fParts.push(`<filter${attrs(fAttrs)}><autoFilter></autoFilter></filter>`);
1739
- }
1740
- fParts.push("</filters>");
1741
- p.push(fParts.join(""));
1742
- }
1743
- if (o.rowHierarchiesUsage && o.rowHierarchiesUsage.length > 0) {
1744
- const rhu = o.rowHierarchiesUsage;
1745
- p.push(`<rowHierarchiesUsage count="${rhu.length}">${rhu.map((h) => `<rowHierarchyUsage hierarchyUsage="${h.hierarchyUsage}"/>`).join("")}</rowHierarchiesUsage>`);
1746
- }
1747
- if (o.colHierarchiesUsage && o.colHierarchiesUsage.length > 0) {
1748
- const chu = o.colHierarchiesUsage;
1749
- p.push(`<colHierarchiesUsage count="${chu.length}">${chu.map((h) => `<colHierarchyUsage hierarchyUsage="${h.hierarchyUsage}"/>`).join("")}</colHierarchiesUsage>`);
1750
- }
1751
- p.push("</pivotTableDefinition>");
1752
- return p.join("");
1753
- }
1754
- function buildFieldOverrideAttrs(fo) {
1755
- const a = [];
1756
- if (fo.allDrilled) a.push("allDrilled=\"1\"");
1757
- if (fo.autoShow) a.push("autoShow=\"1\"");
1758
- if (fo.countSubtotal) a.push("countSubtotal=\"1\"");
1759
- if (fo.dataSourceSort) a.push("dataSourceSort=\"1\"");
1760
- if (fo.defaultAttributeDrillState) a.push("defaultAttributeDrillState=\"1\"");
1761
- if (fo.hiddenLevel) a.push("hiddenLevel=\"1\"");
1762
- if (fo.hideNewItems) a.push("hideNewItems=\"1\"");
1763
- if (fo.insertBlankRow) a.push("insertBlankRow=\"1\"");
1764
- if (fo.insertPageBreak) a.push("insertPageBreak=\"1\"");
1765
- if (fo.itemPageCount) a.push("itemPageCount=\"1\"");
1766
- if (fo.measureFilter) a.push("measureFilter=\"1\"");
1767
- if (fo.nonAutoSortDefault) a.push("nonAutoSortDefault=\"1\"");
1768
- if (fo.productSubtotal) a.push("productSubtotal=\"1\"");
1769
- if (fo.rankBy !== void 0) a.push(`rankBy="${fo.rankBy}"`);
1770
- if (fo.serverField) a.push("serverField=\"1\"");
1771
- if (fo.showDropDowns) a.push("showDropDowns=\"1\"");
1772
- if (fo.showPropAsCaption) a.push("showPropAsCaption=\"1\"");
1773
- if (fo.showPropCell) a.push("showPropCell=\"1\"");
1774
- if (fo.showPropTip) a.push("showPropTip=\"1\"");
1775
- if (fo.stdDevPSubtotal) a.push("stdDevPSubtotal=\"1\"");
1776
- if (fo.stdDevSubtotal) a.push("stdDevSubtotal=\"1\"");
1777
- if (fo.subtotalCaption) a.push(`subtotalCaption="${escapeXml(fo.subtotalCaption)}"`);
1778
- if (fo.topAutoShow) a.push("topAutoShow=\"1\"");
1779
- if (fo.uniqueMemberProperty) a.push("uniqueMemberProperty=\"1\"");
1780
- if (fo.varPSubtotal) a.push("varPSubtotal=\"1\"");
1781
- if (fo.varSubtotal) a.push("varSubtotal=\"1\"");
1782
- return a.join(" ");
1783
- }
1784
- function buildPivotFields(o, sd, rowIndices, colIndices, dataIndices, pageIndices) {
1785
- const fieldNames = sd.fieldNames;
1786
- const parts = [`<pivotFields count="${fieldNames.length}">`];
1787
- for (let i = 0; i < fieldNames.length; i++) {
1788
- const isRow = rowIndices.includes(i);
1789
- const isCol = colIndices.includes(i);
1790
- const isData = dataIndices.includes(i);
1791
- const isPage = pageIndices.includes(i);
1792
- const override = o.fieldOverrides?.find((fo) => fo.field === fieldNames[i]);
1793
- const extraAttrs = override ? buildFieldOverrideAttrs(override) : "";
1794
- if (isData) {
1795
- const dataFieldIdx = dataIndices.indexOf(i);
1796
- const df = o.data[dataFieldIdx];
1797
- const dfAttrs = ["dataField=\"1\"", "showAll=\"0\""];
1798
- if (extraAttrs) dfAttrs.push(extraAttrs);
1799
- if (df?.showDataAs) dfAttrs.push(`showDataAs="${df.showDataAs}"`);
1800
- if (df?.baseField !== void 0) dfAttrs.push(`baseField="${df.baseField}"`);
1801
- if (df?.baseItem !== void 0) dfAttrs.push(`baseItem="${df.baseItem}"`);
1802
- if (o.autoSortScope) parts.push(`<pivotField ${dfAttrs.join(" ")}><autoSortScope>${buildPivotAreaXml(o.autoSortScope)}</autoSortScope></pivotField>`);
1803
- else parts.push(`<pivotField ${dfAttrs.join(" ")}/>`);
1804
- } else if (isRow) {
1805
- const uniqueVals = collectUniqueValues(sd.records, i);
1806
- const rAttrs = extraAttrs ? ` axis="axisRow" showAll="0" ${extraAttrs}` : " axis=\"axisRow\" showAll=\"0\"";
1807
- parts.push(`<pivotField${rAttrs}>`);
1808
- parts.push(`<items count="${uniqueVals.length + 1}">`);
1809
- for (let j = 0; j < uniqueVals.length; j++) parts.push(`<item x="${j}"/>`);
1810
- parts.push(`<item t="default"${override?.defaultItemSd === false ? " sd=\"0\"" : ""}/>`);
1811
- parts.push("</items></pivotField>");
1812
- } else if (isCol) {
1813
- const uniqueVals = collectUniqueValues(sd.records, i);
1814
- const cAttrs = extraAttrs ? ` axis="axisCol" showAll="0" ${extraAttrs}` : " axis=\"axisCol\" showAll=\"0\"";
1815
- parts.push(`<pivotField${cAttrs}>`);
1816
- parts.push(`<items count="${uniqueVals.length + 1}">`);
1817
- for (let j = 0; j < uniqueVals.length; j++) parts.push(`<item x="${j}"/>`);
1818
- parts.push(`<item t="default"${override?.defaultItemSd === false ? " sd=\"0\"" : ""}/>`);
1819
- parts.push("</items></pivotField>");
1820
- } else if (isPage) {
1821
- const uniqueVals = collectUniqueValues(sd.records, i);
1822
- const pAttrs = extraAttrs ? ` axis="axisPage" showAll="0" ${extraAttrs}` : " axis=\"axisPage\" showAll=\"0\"";
1823
- parts.push(`<pivotField${pAttrs}>`);
1824
- parts.push(`<items count="${uniqueVals.length + 1}">`);
1825
- for (let j = 0; j < uniqueVals.length; j++) parts.push(`<item x="${j}"/>`);
1826
- parts.push(`<item t="default"${override?.defaultItemSd === false ? " sd=\"0\"" : ""}/>`);
1827
- parts.push("</items></pivotField>");
1828
- } else {
1829
- const nAttrs = extraAttrs ? ` showAll="0" ${extraAttrs}` : " showAll=\"0\"";
1830
- parts.push(`<pivotField${nAttrs}/>`);
1831
- }
1832
- }
1833
- parts.push("</pivotFields>");
1834
- return parts.join("");
1835
- }
1836
- function buildPageFields(o, pageIndices) {
1837
- if (pageIndices.length === 0) return "";
1838
- const parts = [`<pageFields count="${pageIndices.length}">`];
1839
- for (let i = 0; i < pageIndices.length; i++) {
1840
- const cap = o.pageCaptions?.[i];
1841
- const capAttr = cap ? ` cap="${escapeXml(cap)}"` : "";
1842
- parts.push(`<pageField fld="${pageIndices[i]}" hier="${i}"${capAttr}/>`);
1843
- }
1844
- parts.push("</pageFields>");
1845
- return parts.join("");
1846
- }
1847
- function buildRowFields(rowIndices) {
1848
- if (rowIndices.length === 0) return "<rowFields count=\"0\"/>";
1849
- const parts = [`<rowFields count="${rowIndices.length}">`];
1850
- for (const idx of rowIndices) parts.push(`<field x="${idx}"/>`);
1851
- parts.push("</rowFields>");
1852
- return parts.join("");
1853
- }
1854
- function buildRowItems(sd, rowIndices) {
1855
- if (rowIndices.length === 0) return "<rowItems count=\"1\"><i/></rowItems>";
1856
- const allUniqueCounts = [];
1857
- for (const idx of rowIndices) allUniqueCounts.push(collectUniqueValues(sd.records, idx).length);
1858
- if (rowIndices.length === 1) {
1859
- const count = allUniqueCounts[0] ?? 0;
1860
- const parts = [`<rowItems count="${count + 1}">`];
1861
- for (let i = 0; i < count; i++) parts.push(`<i><x v="${i}"/></i>`);
1862
- parts.push(`<i t="grand"><x/></i>`);
1863
- parts.push("</rowItems>");
1864
- return parts.join("");
1865
- }
1866
- const combos = cartesianOfCounts(allUniqueCounts);
1867
- const rowItems = [];
1868
- for (const combo of combos) rowItems.push(`<i>${combo.map((v) => `<x v="${v}"/>`).join("")}</i>`);
1869
- rowItems.push(`<i t="grand">${rowIndices.map(() => "<x/>").join("")}</i>`);
1870
- return `<rowItems count="${rowItems.length}">${rowItems.join("")}</rowItems>`;
1871
- }
1872
- function buildColFields(colIndices) {
1873
- if (colIndices.length === 0) return "<colFields count=\"0\"/>";
1874
- const parts = [`<colFields count="${colIndices.length}">`];
1875
- for (const idx of colIndices) parts.push(`<field x="${idx}"/>`);
1876
- parts.push("</colFields>");
1877
- return parts.join("");
1878
- }
1879
- function buildColItems(sd, colIndices, dataFields) {
1880
- if (colIndices.length > 0) {
1881
- const allUniqueCounts = [];
1882
- for (const idx of colIndices) allUniqueCounts.push(collectUniqueValues(sd.records, idx).length);
1883
- const combos = cartesianOfCounts(allUniqueCounts);
1884
- const items = [];
1885
- for (const combo of combos) items.push(`<i>${combo.map((v) => `<x v="${v}"/>`).join("")}</i>`);
1886
- items.push(`<i t="grand">${colIndices.map(() => "<x/>").join("")}</i>`);
1887
- return `<colItems count="${items.length}">${items.join("")}</colItems>`;
1888
- }
1889
- if (dataFields.length > 1) {
1890
- const items = dataFields.map((_, i) => `<i><x v="${i}"/></i>`);
1891
- return `<colItems count="${items.length}">${items.join("")}</colItems>`;
1892
- }
1893
- return "<colItems count=\"1\"><i/></colItems>";
1894
- }
1895
- function buildDataFields(dataFields, dataFieldIndices) {
1896
- if (dataFields.length === 0) return "<dataFields count=\"0\"/>";
1897
- const parts = [`<dataFields count="${dataFields.length}">`];
1898
- for (const [i, df] of dataFields.entries()) {
1899
- const subtotal = df.summarize ?? "sum";
1900
- const dfAttrs = [
1901
- `name="${escapeXml(df.name ?? `${subtotal === "sum" ? "Sum" : subtotal} of ${df.field}`)}"`,
1902
- `fld="${dataFieldIndices[i] ?? 0}"`,
1903
- `subtotal="${subtotal}"`
1904
- ];
1905
- if (df.showDataAs) dfAttrs.push(`showDataAs="${df.showDataAs}"`);
1906
- if (df.baseField !== void 0) dfAttrs.push(`baseField="${df.baseField}"`);
1907
- if (df.baseItem !== void 0) dfAttrs.push(`baseItem="${df.baseItem}"`);
1908
- parts.push(`<dataField ${dfAttrs.join(" ")}/>`);
1909
- }
1910
- parts.push("</dataFields>");
1911
- return parts.join("");
1912
- }
1913
- function computeLocationRef(sd, location, rowFieldIndices, colFieldIndices, dataFields) {
1914
- const match = (location.split(":")[0] ?? location).match(/^([A-Z]+)(\d+)$/);
1915
- if (!match) return location;
1916
- const startCol = match[1] ?? "";
1917
- const startRow = parseInt(match[2] ?? "0", 10);
1918
- let rowCount = 1;
1919
- const rowFieldIndex0 = rowFieldIndices[0];
1920
- if (rowFieldIndex0 !== void 0) rowCount += collectUniqueValues(sd.records, rowFieldIndex0).length;
1921
- rowCount += 1;
1922
- let colCount = Math.max(rowFieldIndices.length, 1);
1923
- const colFieldIndex0 = colFieldIndices[0];
1924
- if (colFieldIndex0 !== void 0) colCount += collectUniqueValues(sd.records, colFieldIndex0).length;
1925
- else if (dataFields.length > 1) colCount += dataFields.length - 1;
1926
- colCount += 1;
1927
- return `${startCol}${startRow}:${colIndexToLetter(letterToColIndex(startCol) + colCount - 1)}${startRow + rowCount - 1}`;
1928
- }
1929
- function buildPivotHierarchies(hierarchies) {
1930
- const parts = [`<pivotHierarchies count="${hierarchies.length}">`];
1931
- for (const h of hierarchies) {
1932
- const hAttrs = [];
1933
- if (h.outline) hAttrs.push("outline=\"1\"");
1934
- if (h.multipleItemSelectionAllowed) hAttrs.push("multipleItemSelectionAllowed=\"1\"");
1935
- if (h.subtotalTop) hAttrs.push("subtotalTop=\"1\"");
1936
- if (h.showInFieldList === false) hAttrs.push("showInFieldList=\"0\"");
1937
- if (h.dragToRow === false) hAttrs.push("dragToRow=\"0\"");
1938
- if (h.dragToCol === false) hAttrs.push("dragToCol=\"0\"");
1939
- if (h.dragToPage === false) hAttrs.push("dragToPage=\"0\"");
1940
- if (h.dragToData) hAttrs.push("dragToData=\"1\"");
1941
- if (h.dragOff === false) hAttrs.push("dragOff=\"0\"");
1942
- if (h.includeNewItemsInFilter) hAttrs.push("includeNewItemsInFilter=\"1\"");
1943
- if (h.caption) hAttrs.push(`caption="${escapeXml(h.caption)}"`);
1944
- const inner = (h.memberProperties ? `<mps count="${h.memberProperties.length}">${h.memberProperties.map((mp) => {
1945
- const mpAttrs = [`field="${mp.field}"`];
1946
- if (mp.name !== void 0) mpAttrs.push(`name="${escapeXml(mp.name)}"`);
1947
- if (mp.showCell) mpAttrs.push("showCell=\"1\"");
1948
- if (mp.showTip) mpAttrs.push("showTip=\"1\"");
1949
- if (mp.showAsCaption) mpAttrs.push("showAsCaption=\"1\"");
1950
- return `<mp ${mpAttrs.join(" ")}/>`;
1951
- }).join("")}</mps>` : "") + (h.members ? `<members count="${h.members.length}">${h.members.map((m) => `<member name="${escapeXml(m.name)}"${m.level !== void 0 ? ` level="${m.level}"` : ""}/>`).join("")}</members>` : "");
1952
- if (inner) parts.push(`<pivotHierarchy ${hAttrs.join(" ")}>${inner}</pivotHierarchy>`);
1953
- else parts.push(`<pivotHierarchy ${hAttrs.join(" ")}/>`);
1954
- }
1955
- parts.push("</pivotHierarchies>");
1956
- return parts.join("");
1957
- }
1958
- function buildPivotAreaXml(area) {
1959
- const aAttrs = [];
1960
- if (area.field !== void 0) aAttrs.push(`field="${area.field}"`);
1961
- if (area.type) aAttrs.push(`type="${area.type}"`);
1962
- if (area.dataOnly === false) aAttrs.push("dataOnly=\"0\"");
1963
- if (area.labelOnly) aAttrs.push("labelOnly=\"1\"");
1964
- if (area.grandRow) aAttrs.push("grandRow=\"1\"");
1965
- if (area.grandCol) aAttrs.push("grandCol=\"1\"");
1966
- if (area.cacheIndex) aAttrs.push("cacheIndex=\"1\"");
1967
- if (area.outline === false) aAttrs.push("outline=\"0\"");
1968
- if (area.offset) aAttrs.push(`offset="${escapeXml(area.offset)}"`);
1969
- if (area.collapsedLevelsAreSubtotals) aAttrs.push("collapsedLevelsAreSubtotals=\"1\"");
1970
- if (area.axis) aAttrs.push(`axis="${area.axis}"`);
1971
- if (area.fieldPosition !== void 0) aAttrs.push(`fieldPosition="${area.fieldPosition}"`);
1972
- const refsXml = area.references ? buildPivotAreaReferences(area.references) : "";
1973
- if (refsXml) return `<pivotArea ${aAttrs.join(" ")}>${refsXml}</pivotArea>`;
1974
- return `<pivotArea ${aAttrs.join(" ")}/>`;
1975
- }
1976
- function buildPivotAreaReferences(refs) {
1977
- const parts = [`<references count="${refs.length}">`];
1978
- for (const ref of refs) {
1979
- const rAttrs = [];
1980
- if (ref.field !== void 0) rAttrs.push(`field="${ref.field}"`);
1981
- if (ref.count !== void 0) rAttrs.push(`count="${ref.count}"`);
1982
- if (ref.selected === false) rAttrs.push("selected=\"0\"");
1983
- if (ref.byPosition) rAttrs.push("byPosition=\"1\"");
1984
- if (ref.relative) rAttrs.push("relative=\"1\"");
1985
- if (ref.defaultSubtotal) rAttrs.push("defaultSubtotal=\"1\"");
1986
- const xXml = ref.x ? ref.x.map((v) => `<x v="${v}"/>`).join("") : "";
1987
- if (xXml) parts.push(`<reference ${rAttrs.join(" ")}>${xXml}</reference>`);
1988
- else parts.push(`<reference ${rAttrs.join(" ")}/>`);
1989
- }
1990
- parts.push("</references>");
1991
- return parts.join("");
1992
- }
1993
- function letterToColIndex(letters) {
1994
- let col = 0;
1995
- for (let i = 0; i < letters.length; i++) col = col * 26 + (letters.charCodeAt(i) - 64);
1996
- return col;
1997
- }
1998
- function colIndexToLetter(col) {
1999
- let result = "";
2000
- let n = col;
2001
- while (n > 0) {
2002
- n--;
2003
- result = String.fromCharCode(65 + n % 26) + result;
2004
- n = Math.floor(n / 26);
2005
- }
2006
- return result;
2007
- }
2008
- function cartesianOfCounts(counts) {
2009
- if (counts.length === 0) return [[]];
2010
- let result = [[]];
2011
- for (const count of counts) {
2012
- const next = [];
2013
- for (const prefix of result) for (let i = 0; i < count; i++) next.push([...prefix, i]);
2014
- result = next;
2015
- }
2016
- return result;
2017
- }
2018
- function parsePivotArea(el) {
2019
- const result = {};
2020
- const field = attrNum(el, "field");
2021
- if (field !== void 0) result.field = field;
2022
- const typeVal = attr(el, "type");
2023
- if (typeVal) result.type = typeVal;
2024
- if (attr(el, "dataOnly") === "0") result.dataOnly = false;
2025
- if (attr(el, "labelOnly") === "1") result.labelOnly = true;
2026
- if (attr(el, "grandRow") === "1") result.grandRow = true;
2027
- if (attr(el, "grandCol") === "1") result.grandCol = true;
2028
- if (attr(el, "cacheIndex") === "1") result.cacheIndex = true;
2029
- if (attr(el, "outline") === "0") result.outline = false;
2030
- if (attr(el, "offset")) result.offset = attr(el, "offset");
2031
- if (attr(el, "collapsedLevelsAreSubtotals") === "1") result.collapsedLevelsAreSubtotals = true;
2032
- const axisVal = attr(el, "axis");
2033
- if (axisVal) result.axis = axisVal;
2034
- const fp = attrNum(el, "fieldPosition");
2035
- if (fp !== void 0) result.fieldPosition = fp;
2036
- const refsEl = findChild(el, "references");
2037
- if (refsEl) {
2038
- const refs = [];
2039
- for (const rEl of refsEl.elements ?? []) {
2040
- if (rEl.name !== "reference") continue;
2041
- const ref = {};
2042
- const rField = attrNum(rEl, "field");
2043
- if (rField !== void 0) ref.field = rField;
2044
- const rCount = attrNum(rEl, "count");
2045
- if (rCount !== void 0) ref.count = rCount;
2046
- if (attr(rEl, "selected") === "0") ref.selected = false;
2047
- if (attr(rEl, "byPosition") === "1") ref.byPosition = true;
2048
- if (attr(rEl, "relative") === "1") ref.relative = true;
2049
- if (attr(rEl, "defaultSubtotal") === "1") ref.defaultSubtotal = true;
2050
- const xArr = [];
2051
- for (const xEl of rEl.elements ?? []) if (xEl.name === "x") {
2052
- const v = attrNum(xEl, "v");
2053
- if (v !== void 0) xArr.push(v);
2054
- }
2055
- if (xArr.length > 0) ref.x = xArr;
2056
- refs.push(ref);
2057
- }
2058
- result.references = refs;
2059
- }
2060
- return result;
2061
- }
2062
- //#endregion
2063
- //#region src/parts/pivot-cache.ts
2064
- const pivotCacheDefDesc = {
2065
- kind: "custom",
2066
- stringify(opts, _ctx) {
2067
- return stringifyPivotCacheDef(opts.sourceRef, opts.sourceSheet, opts.sourceData, opts.recordsRid, opts.cacheDefOpts);
2068
- },
2069
- parse(el, _ctx) {
2070
- const result = {};
2071
- if (attr(el, "invalid") === "1") result.invalid = true;
2072
- if (attr(el, "saveData") === "0") result.saveData = false;
2073
- if (attr(el, "optimizeMemory") === "1") result.optimizeMemory = true;
2074
- if (attr(el, "enableRefresh") === "0") result.enableRefresh = false;
2075
- if (attr(el, "refreshedBy")) result.refreshedBy = attr(el, "refreshedBy");
2076
- const rd = attrNum(el, "refreshedDate");
2077
- if (rd !== void 0) result.refreshedDate = rd;
2078
- if (attr(el, "refreshedDateIso")) result.refreshedDateIso = attr(el, "refreshedDateIso");
2079
- if (attr(el, "backgroundQuery") === "1") result.backgroundQuery = true;
2080
- const mil = attrNum(el, "missingItemsLimit");
2081
- if (mil !== void 0) result.missingItemsLimit = mil;
2082
- if (attr(el, "upgradeOnRefresh") === "1") result.upgradeOnRefresh = true;
2083
- if (attr(el, "supportSubquery") === "1") result.supportSubquery = true;
2084
- if (attr(el, "supportAdvancedDrill") === "1") result.supportAdvancedDrill = true;
2085
- const recordCount = attrNum(el, "recordCount");
2086
- if (recordCount !== void 0) result.recordCount = recordCount;
2087
- const csEl = findChild(el, "cacheSource");
2088
- if (csEl) {
2089
- result.sourceType = attr(csEl, "type");
2090
- const wssEl = findChild(csEl, "worksheetSource");
2091
- if (wssEl) {
2092
- const wss = {};
2093
- if (attr(wssEl, "ref")) wss.ref = attr(wssEl, "ref");
2094
- if (attr(wssEl, "sheet")) wss.sheet = attr(wssEl, "sheet");
2095
- result.worksheetSource = wss;
2096
- }
2097
- }
2098
- const cfEl = findChild(el, "cacheFields");
2099
- if (cfEl) {
2100
- const fields = [];
2101
- for (const fEl of cfEl.elements ?? []) {
2102
- if (fEl.name !== "cacheField") continue;
2103
- const field = {};
2104
- if (attr(fEl, "name")) field.name = attr(fEl, "name");
2105
- if (attrNum(fEl, "numFmtId") !== void 0) field.numFmtId = attrNum(fEl, "numFmtId");
2106
- const siEl = findChild(fEl, "sharedItems");
2107
- if (siEl) {
2108
- const items = [];
2109
- for (const siChild of siEl.elements ?? []) {
2110
- const v = attr(siChild, "v");
2111
- if (v !== void 0) items.push(isNaN(Number(v)) ? v : Number(v));
2112
- }
2113
- field.sharedItems = items;
2114
- }
2115
- fields.push(field);
2116
- }
2117
- result.cacheFields = fields;
2118
- }
2119
- return result;
2120
- }
2121
- };
2122
- const pivotCacheRecordsDesc = {
2123
- kind: "custom",
2124
- stringify(opts, _ctx) {
2125
- return stringifyPivotCacheRecords(opts.sourceData);
2126
- },
2127
- parse(el, _ctx) {
2128
- const records = [];
2129
- for (const rEl of el.elements ?? []) {
2130
- if (rEl.name !== "r") continue;
2131
- const record = [];
2132
- for (const fEl of rEl.elements ?? []) {
2133
- let entry;
2134
- if (fEl.name === "x") entry = {
2135
- type: "string",
2136
- v: attrNum(fEl, "v") ?? 0
2137
- };
2138
- else if (fEl.name === "n") {
2139
- const v = attr(fEl, "v");
2140
- entry = {
2141
- type: "number",
2142
- v: v !== void 0 ? Number(v) : 0
2143
- };
2144
- } else if (fEl.name === "d") entry = {
2145
- type: "date",
2146
- v: attr(fEl, "v") ?? ""
2147
- };
2148
- else if (fEl.name === "m") entry = { type: "missing" };
2149
- else continue;
2150
- record.push(entry);
2151
- }
2152
- records.push(record);
2153
- }
2154
- return { records };
2155
- }
2156
- };
2157
- function stringifyPivotCacheDef(sourceRef, sourceSheet, sourceData, recordsRid, cacheDefOpts) {
2158
- const p = [];
2159
- const rootAttrs = [
2160
- "xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"",
2161
- "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"",
2162
- `r:id="${escapeXml(recordsRid)}"`,
2163
- `recordCount="${sourceData.records.length}"`,
2164
- "createdVersion=\"6\"",
2165
- "refreshedVersion=\"6\"",
2166
- "minRefreshableVersion=\"3\""
2167
- ];
2168
- if (cacheDefOpts) {
2169
- const cd = cacheDefOpts;
2170
- if (cd.invalid) rootAttrs.push("invalid=\"1\"");
2171
- if (cd.saveData === false) rootAttrs.push("saveData=\"0\"");
2172
- if (cd.optimizeMemory) rootAttrs.push("optimizeMemory=\"1\"");
2173
- if (cd.enableRefresh === false) rootAttrs.push("enableRefresh=\"0\"");
2174
- if (cd.refreshedBy) rootAttrs.push(`refreshedBy="${escapeXml(cd.refreshedBy)}"`);
2175
- if (cd.refreshedDate !== void 0) rootAttrs.push(`refreshedDate="${cd.refreshedDate}"`);
2176
- if (cd.refreshedDateIso) rootAttrs.push(`refreshedDateIso="${escapeXml(cd.refreshedDateIso)}"`);
2177
- if (cd.backgroundQuery) rootAttrs.push("backgroundQuery=\"1\"");
2178
- if (cd.missingItemsLimit !== void 0) rootAttrs.push(`missingItemsLimit="${cd.missingItemsLimit}"`);
2179
- if (cd.upgradeOnRefresh) rootAttrs.push("upgradeOnRefresh=\"1\"");
2180
- if (cd.supportSubquery) rootAttrs.push("supportSubquery=\"1\"");
2181
- if (cd.supportAdvancedDrill) rootAttrs.push("supportAdvancedDrill=\"1\"");
2182
- }
2183
- p.push(`<pivotCacheDefinition ${rootAttrs.join(" ")}>`);
2184
- if (cacheDefOpts?.consolidation) {
2185
- const con = cacheDefOpts.consolidation;
2186
- const conParts = ["<cacheSource type=\"consolidation\"><consolidation"];
2187
- if (con.autoPage === false) conParts.push(" autoPage=\"0\"");
2188
- conParts.push(">");
2189
- if (con.pages && con.pages.length > 0) {
2190
- conParts.push(`<pages count="${con.pages.length}">`);
2191
- for (const pg of con.pages) {
2192
- const pgItems = pg.items ?? [];
2193
- conParts.push(`<page${pgItems.length ? ` count="${pgItems.length}"` : ""}>`);
2194
- for (const pi of pgItems) conParts.push(`<pageItem name="${escapeXml(pi.name)}"/>`);
2195
- conParts.push("</page>");
2196
- }
2197
- conParts.push("</pages>");
2198
- }
2199
- conParts.push(`<rangeSets count="${con.rangeSets.length}">`);
2200
- for (const rs of con.rangeSets) {
2201
- const rsAttrs = [];
2202
- if (rs.i1 !== void 0) rsAttrs.push(`i1="${rs.i1}"`);
2203
- if (rs.i2 !== void 0) rsAttrs.push(`i2="${rs.i2}"`);
2204
- if (rs.i3 !== void 0) rsAttrs.push(`i3="${rs.i3}"`);
2205
- if (rs.i4 !== void 0) rsAttrs.push(`i4="${rs.i4}"`);
2206
- if (rs.ref) rsAttrs.push(`ref="${escapeXml(rs.ref)}"`);
2207
- if (rs.name) rsAttrs.push(`name="${escapeXml(rs.name)}"`);
2208
- if (rs.sheet) rsAttrs.push(`sheet="${escapeXml(rs.sheet)}"`);
2209
- if (rs.rId) rsAttrs.push(`r:id="${escapeXml(rs.rId)}"`);
2210
- conParts.push(`<rangeSet ${rsAttrs.join(" ")}/>`);
2211
- }
2212
- conParts.push("</rangeSets></consolidation></cacheSource>");
2213
- p.push(conParts.join(""));
2214
- } else p.push(`<cacheSource type="worksheet"><worksheetSource ref="${escapeXml(sourceRef)}" sheet="${escapeXml(sourceSheet)}"/></cacheSource>`);
2215
- const fieldNames = sourceData.fieldNames;
2216
- p.push(`<cacheFields count="${fieldNames.length}">`);
2217
- for (let i = 0; i < fieldNames.length; i++) {
2218
- const fieldName = fieldNames[i] ?? "";
2219
- const numeric = isNumericField(sourceData.records, i);
2220
- const uniqueVals = collectUniqueValues(sourceData.records, i);
2221
- if (numeric) {
2222
- let min = Infinity, max = -Infinity;
2223
- for (const row of sourceData.records) {
2224
- const v = row[i];
2225
- if (typeof v === "number") {
2226
- if (v < min) min = v;
2227
- if (v > max) max = v;
2228
- }
2229
- }
2230
- if (!isFinite(min)) {
2231
- min = 0;
2232
- max = 0;
2233
- }
2234
- const allInteger = sourceData.records.every((row) => typeof row[i] === "number" && Number.isInteger(row[i]));
2235
- const cfOverride = cacheDefOpts?.cacheFieldOverrides?.get(i);
2236
- const cfExtraAttrs = [];
2237
- const siExtraAttrs = [];
2238
- if (cfOverride) {
2239
- if (cfOverride.databaseField) cfExtraAttrs.push("databaseField=\"1\"");
2240
- if (cfOverride.level !== void 0) cfExtraAttrs.push(`level="${cfOverride.level}"`);
2241
- if (cfOverride.mappingCount !== void 0) cfExtraAttrs.push(`mappingCount="${cfOverride.mappingCount}"`);
2242
- if (cfOverride.memberPropertyField !== void 0) cfExtraAttrs.push(`memberPropertyField="${cfOverride.memberPropertyField}"`);
2243
- if (cfOverride.propertyName) cfExtraAttrs.push(`propertyName="${escapeXml(cfOverride.propertyName)}"`);
2244
- if (cfOverride.serverField) cfExtraAttrs.push("serverField=\"1\"");
2245
- if (cfOverride.uniqueList) cfExtraAttrs.push("uniqueList=\"1\"");
2246
- if (cfOverride.containsMixedTypes) siExtraAttrs.push("containsMixedTypes=\"1\"");
2247
- if (cfOverride.containsNonDate) siExtraAttrs.push("containsNonDate=\"1\"");
2248
- if (cfOverride.longText) siExtraAttrs.push("longText=\"1\"");
2249
- }
2250
- p.push(`<cacheField name="${escapeXml(fieldName)}" ${cfExtraAttrs.length ? cfExtraAttrs.join(" ") + " " : ""}numFmtId="0"><sharedItems containsSemiMixedTypes="0" containsString="0" containsNumber="1" containsInteger="${allInteger ? "1" : "0"}" minValue="${min}" maxValue="${max}" count="${uniqueVals.length}"${siExtraAttrs.length ? " " + siExtraAttrs.join(" ") : ""}>`);
2251
- for (const v of uniqueVals) if (v === null) p.push("<m/>");
2252
- else if (v instanceof Date) p.push(`<d v="${v.toISOString().replace(/\.\d{3}Z$/, "Z")}"/>`);
2253
- else p.push(`<n v="${v}"/>`);
2254
- p.push("</sharedItems></cacheField>");
2255
- } else {
2256
- let hasDate = false, hasMissing = false;
2257
- for (const v of uniqueVals) {
2258
- if (v instanceof Date) hasDate = true;
2259
- if (v === null) hasMissing = true;
2260
- }
2261
- const siAttrs = [`count="${uniqueVals.length}"`];
2262
- if (hasDate) siAttrs.push("containsDate=\"1\"");
2263
- if (hasMissing) siAttrs.push("containsBlank=\"1\"");
2264
- const cfOverride = cacheDefOpts?.cacheFieldOverrides?.get(i);
2265
- const cfExtraAttrs = [];
2266
- if (cfOverride) {
2267
- if (cfOverride.databaseField) cfExtraAttrs.push("databaseField=\"1\"");
2268
- if (cfOverride.level !== void 0) cfExtraAttrs.push(`level="${cfOverride.level}"`);
2269
- if (cfOverride.mappingCount !== void 0) cfExtraAttrs.push(`mappingCount="${cfOverride.mappingCount}"`);
2270
- if (cfOverride.memberPropertyField !== void 0) cfExtraAttrs.push(`memberPropertyField="${cfOverride.memberPropertyField}"`);
2271
- if (cfOverride.propertyName) cfExtraAttrs.push(`propertyName="${escapeXml(cfOverride.propertyName)}"`);
2272
- if (cfOverride.serverField) cfExtraAttrs.push("serverField=\"1\"");
2273
- if (cfOverride.uniqueList) cfExtraAttrs.push("uniqueList=\"1\"");
2274
- if (cfOverride.containsMixedTypes) siAttrs.push("containsMixedTypes=\"1\"");
2275
- if (cfOverride.containsNonDate) siAttrs.push("containsNonDate=\"1\"");
2276
- if (cfOverride.longText) siAttrs.push("longText=\"1\"");
2277
- }
2278
- p.push(`<cacheField name="${escapeXml(fieldName)}" ${cfExtraAttrs.length ? cfExtraAttrs.join(" ") + " " : ""}numFmtId="0"><sharedItems ${siAttrs.join(" ")}>`);
2279
- for (const v of uniqueVals) if (v === null) p.push("<m/>");
2280
- else if (v instanceof Date) p.push(`<d v="${v.toISOString().replace(/\.\d{3}Z$/, "Z")}"/>`);
2281
- else p.push(`<s v="${escapeXml(String(v))}"/>`);
2282
- p.push("</sharedItems>");
2283
- const fg = cacheDefOpts?.fieldGroups?.get(i);
2284
- if (fg) {
2285
- const fgParts = ["<fieldGroup"];
2286
- if (fg.parent !== void 0) fgParts.push(` par="${fg.parent}"`);
2287
- if (fg.base !== void 0) fgParts.push(` base="${fg.base}"`);
2288
- fgParts.push(">");
2289
- if (fg.rangePr) {
2290
- const rp = fg.rangePr;
2291
- const rpAttrs = [];
2292
- if (rp.autoStart === false) rpAttrs.push("autoStart=\"0\"");
2293
- if (rp.autoEnd === false) rpAttrs.push("autoEnd=\"0\"");
2294
- if (rp.groupBy && rp.groupBy !== "range") rpAttrs.push(`groupBy="${rp.groupBy}"`);
2295
- if (rp.startNum !== void 0) rpAttrs.push(`startNum="${rp.startNum}"`);
2296
- if (rp.endNum !== void 0) rpAttrs.push(`endNum="${rp.endNum}"`);
2297
- if (rp.startDate) rpAttrs.push(`startDate="${escapeXml(rp.startDate)}"`);
2298
- if (rp.endDate) rpAttrs.push(`endDate="${escapeXml(rp.endDate)}"`);
2299
- if (rp.groupInterval !== void 0) rpAttrs.push(`groupInterval="${rp.groupInterval}"`);
2300
- fgParts.push(`<rangePr${rpAttrs.length ? " " + rpAttrs.join(" ") : ""}/>`);
2301
- }
2302
- if (fg.discretePr && fg.discretePr.length > 0) {
2303
- fgParts.push(`<discretePr count="${fg.discretePr.length}">`);
2304
- for (const idx of fg.discretePr) fgParts.push(`<x v="${idx}"/>`);
2305
- fgParts.push("</discretePr>");
2306
- }
2307
- if (fg.groupItems && fg.groupItems.length > 0) {
2308
- fgParts.push(`<groupItems count="${fg.groupItems.length}">`);
2309
- for (const gi of fg.groupItems) fgParts.push(`<s v="${escapeXml(gi)}"/>`);
2310
- fgParts.push("</groupItems>");
2311
- }
2312
- fgParts.push("</fieldGroup>");
2313
- p.push(fgParts.join(""));
2314
- }
2315
- p.push("</cacheField>");
2316
- }
2317
- }
2318
- p.push("</cacheFields>");
2319
- if (cacheDefOpts?.mpMaps) for (const mp of cacheDefOpts.mpMaps) p.push(`<mpMap x="${mp.x}"/>`);
2320
- if (cacheDefOpts?.olapPr) {
2321
- const ol = cacheDefOpts.olapPr;
2322
- const olAttrs = [];
2323
- if (ol.local) olAttrs.push(` local="${escapeXml(ol.local)}"`);
2324
- if (ol.localConnection) olAttrs.push(` localConnection="${escapeXml(ol.localConnection)}"`);
2325
- if (ol.sendLocale) olAttrs.push(" sendLocale=\"1\"");
2326
- if (ol.rowDrillCount !== void 0) olAttrs.push(` rowDrillCount="${ol.rowDrillCount}"`);
2327
- if (ol.colDrillCount !== void 0) olAttrs.push(` colDrillCount="${ol.colDrillCount}"`);
2328
- if (ol.localRefresh) olAttrs.push(" localRefresh=\"1\"");
2329
- if (ol.serverFill === false) olAttrs.push(" serverFill=\"0\"");
2330
- if (ol.serverNumberFormat === false) olAttrs.push(" serverNumberFormat=\"0\"");
2331
- if (ol.serverFont === false) olAttrs.push(" serverFont=\"0\"");
2332
- if (ol.serverFontColor === false) olAttrs.push(" serverFontColor=\"0\"");
2333
- if (olAttrs.length > 0) p.push(`<olapPr${olAttrs.join("")}/>`);
2334
- }
2335
- if (cacheDefOpts?.cacheHierarchies && cacheDefOpts.cacheHierarchies.length > 0) {
2336
- const chs = cacheDefOpts.cacheHierarchies;
2337
- p.push(`<cacheHierarchies count="${chs.length}">`);
2338
- for (const ch of chs) {
2339
- const chAttrs = [`uniqueName="${escapeXml(ch.uniqueName)}"`, `count="${ch.count}"`];
2340
- if (ch.caption) chAttrs.push(`caption="${escapeXml(ch.caption)}"`);
2341
- if (ch.measure) chAttrs.push("measure=\"1\"");
2342
- if (ch.set) chAttrs.push("set=\"1\"");
2343
- if (ch.parentSet !== void 0) chAttrs.push(`parentSet="${ch.parentSet}"`);
2344
- if (ch.iconSet !== void 0 && ch.iconSet !== 0) chAttrs.push(`iconSet="${ch.iconSet}"`);
2345
- if (ch.attribute) chAttrs.push("attribute=\"1\"");
2346
- if (ch.time) chAttrs.push("time=\"1\"");
2347
- if (ch.keyAttribute) chAttrs.push("keyAttribute=\"1\"");
2348
- if (ch.defaultMemberUniqueName) chAttrs.push(`defaultMemberUniqueName="${escapeXml(ch.defaultMemberUniqueName)}"`);
2349
- if (ch.allUniqueName) chAttrs.push(`allUniqueName="${escapeXml(ch.allUniqueName)}"`);
2350
- if (ch.allCaption) chAttrs.push(`allCaption="${escapeXml(ch.allCaption)}"`);
2351
- if (ch.dimensionUniqueName) chAttrs.push(`dimensionUniqueName="${escapeXml(ch.dimensionUniqueName)}"`);
2352
- if (ch.displayFolder) chAttrs.push(`displayFolder="${escapeXml(ch.displayFolder)}"`);
2353
- if (ch.measureGroup) chAttrs.push(`measureGroup="${escapeXml(ch.measureGroup)}"`);
2354
- if (ch.measures) chAttrs.push("measures=\"1\"");
2355
- if (ch.oneField) chAttrs.push("oneField=\"1\"");
2356
- if (ch.hidden) chAttrs.push("hidden=\"1\"");
2357
- if (ch.memberValueDatatype) chAttrs.push(`memberValueDatatype="${ch.memberValueDatatype}"`);
2358
- if (ch.unbalanced) chAttrs.push("unbalanced=\"1\"");
2359
- if (ch.unbalancedGroup) chAttrs.push("unbalancedGroup=\"1\"");
2360
- const hasGL = ch.groupLevels && ch.groupLevels.length > 0;
2361
- const hasFU = ch.fieldsUsage && ch.fieldsUsage.length > 0;
2362
- if (hasGL || hasFU) {
2363
- p.push(`<cacheHierarchy ${chAttrs.join(" ")}>`);
2364
- if (hasFU) {
2365
- const fuParts = [`<fieldsUsage count="${ch.fieldsUsage.length}">`];
2366
- for (const fu of ch.fieldsUsage) fuParts.push(`<fieldUsage v="${fu.value}"/>`);
2367
- fuParts.push("</fieldsUsage>");
2368
- p.push(fuParts.join(""));
2369
- }
2370
- if (hasGL) {
2371
- const glParts = [`<groupLevels count="${ch.groupLevels.length}">`];
2372
- for (const gl of ch.groupLevels) {
2373
- const glAttrs = [`uniqueName="${escapeXml(gl.uniqueName)}"`, `caption="${escapeXml(gl.caption)}"`];
2374
- if (gl.user) glAttrs.push("user=\"1\"");
2375
- if (gl.customRollUp) glAttrs.push("customRollUp=\"1\"");
2376
- if (gl.groups && gl.groups.length > 0) {
2377
- glParts.push(`<groupLevel ${glAttrs.join(" ")}><groups count="${gl.groups.length}">`);
2378
- for (const lg of gl.groups) {
2379
- const lgAttrs = [
2380
- `name="${escapeXml(lg.name)}"`,
2381
- `uniqueName="${escapeXml(lg.uniqueName)}"`,
2382
- `caption="${escapeXml(lg.caption)}"`
2383
- ];
2384
- if (lg.uniqueParent) lgAttrs.push(`uniqueParent="${escapeXml(lg.uniqueParent)}"`);
2385
- if (lg.id !== void 0) lgAttrs.push(`id="${lg.id}"`);
2386
- glParts.push(`<group ${lgAttrs.join(" ")}><groupMembers count="${lg.members.length}">`);
2387
- for (const gm of lg.members) {
2388
- const gmAttrs = [`uniqueName="${escapeXml(gm.uniqueName)}"`];
2389
- if (gm.group) gmAttrs.push("group=\"1\"");
2390
- glParts.push(`<groupMember ${gmAttrs.join(" ")}/>`);
2391
- }
2392
- glParts.push("</groupMembers></group>");
2393
- }
2394
- glParts.push("</groups></groupLevel>");
2395
- } else glParts.push(`<groupLevel ${glAttrs.join(" ")}/>`);
2396
- }
2397
- glParts.push("</groupLevels>");
2398
- p.push(glParts.join(""));
2399
- }
2400
- p.push("</cacheHierarchy>");
2401
- } else p.push(`<cacheHierarchy ${chAttrs.join(" ")}/>`);
2402
- }
2403
- p.push("</cacheHierarchies>");
2404
- }
2405
- if (cacheDefOpts?.kpis && cacheDefOpts.kpis.length > 0) {
2406
- p.push(`<kpis count="${cacheDefOpts.kpis.length}">`);
2407
- for (const k of cacheDefOpts.kpis) {
2408
- const kAttrs = [`uniqueName="${escapeXml(k.uniqueName)}"`, `value="${escapeXml(k.value)}"`];
2409
- if (k.caption) kAttrs.push(`caption="${escapeXml(k.caption)}"`);
2410
- if (k.displayFolder) kAttrs.push(`displayFolder="${escapeXml(k.displayFolder)}"`);
2411
- if (k.measureGroup) kAttrs.push(`measureGroup="${escapeXml(k.measureGroup)}"`);
2412
- if (k.parent) kAttrs.push(`parent="${escapeXml(k.parent)}"`);
2413
- if (k.goal) kAttrs.push(`goal="${escapeXml(k.goal)}"`);
2414
- if (k.status) kAttrs.push(`status="${escapeXml(k.status)}"`);
2415
- if (k.trend) kAttrs.push(`trend="${escapeXml(k.trend)}"`);
2416
- if (k.weight) kAttrs.push(`weight="${escapeXml(k.weight)}"`);
2417
- if (k.time) kAttrs.push(`time="${escapeXml(k.time)}"`);
2418
- p.push(`<kpi ${kAttrs.join(" ")}/>`);
2419
- }
2420
- p.push("</kpis>");
2421
- }
2422
- if (cacheDefOpts?.measureGroups && cacheDefOpts.measureGroups.length > 0) {
2423
- p.push(`<measureGroups count="${cacheDefOpts.measureGroups.length}">`);
2424
- for (const mg of cacheDefOpts.measureGroups) p.push(`<measureGroup name="${escapeXml(mg.name)}" caption="${escapeXml(mg.caption)}"/>`);
2425
- p.push("</measureGroups>");
2426
- }
2427
- if (cacheDefOpts?.measureDimensionMaps && cacheDefOpts.measureDimensionMaps.length > 0) {
2428
- p.push(`<maps count="${cacheDefOpts.measureDimensionMaps.length}">`);
2429
- for (const m of cacheDefOpts.measureDimensionMaps) {
2430
- const mAttrs = [];
2431
- if (m.measureGroup !== void 0) mAttrs.push(`measureGroup="${m.measureGroup}"`);
2432
- if (m.dimension !== void 0) mAttrs.push(`dimension="${m.dimension}"`);
2433
- p.push(`<map ${mAttrs.join(" ")}/>`);
2434
- }
2435
- p.push("</maps>");
2436
- }
2437
- if (cacheDefOpts?.dimensions && cacheDefOpts.dimensions.length > 0) {
2438
- p.push(`<dimensions count="${cacheDefOpts.dimensions.length}">`);
2439
- for (const d of cacheDefOpts.dimensions) {
2440
- const dAttrs = [
2441
- `name="${escapeXml(d.name)}"`,
2442
- `uniqueName="${escapeXml(d.uniqueName)}"`,
2443
- `caption="${escapeXml(d.caption)}"`
2444
- ];
2445
- if (d.measure) dAttrs.push("measure=\"1\"");
2446
- p.push(`<dimension ${dAttrs.join(" ")}/>`);
2447
- }
2448
- p.push("</dimensions>");
2449
- }
2450
- const cd = cacheDefOpts;
2451
- const hasEntries = cd?.entries && cd.entries.length > 0;
2452
- const hasSets = cd?.sets && cd.sets.length > 0;
2453
- const hasSF = cd?.serverFormats && cd.serverFormats.length > 0;
2454
- const hasQC = cd?.queryCache && cd.queryCache.length > 0;
2455
- if (hasEntries || hasSets || hasSF || hasQC) {
2456
- p.push("<tupleCache>");
2457
- if (hasEntries) {
2458
- const entParts = [`<entries count="${cd.entries.length}">`];
2459
- for (const ent of cd.entries) if (ent.type === "m") entParts.push("<m/>");
2460
- else if (ent.value !== void 0) entParts.push(`<${ent.type} v="${ent.value}"/>`);
2461
- entParts.push("</entries>");
2462
- p.push(entParts.join(""));
2463
- }
2464
- if (hasSets) {
2465
- p.push(`<sets count="${cd.sets.length}">`);
2466
- for (const s of cd.sets) {
2467
- const sAttrs = [`maxRank="${s.maxRank}"`, `setDefinition="${escapeXml(s.setDefinition)}"`];
2468
- if (s.count !== void 0) sAttrs.push(`count="${s.count}"`);
2469
- if (s.sortType && s.sortType !== "none") sAttrs.push(`sortType="${s.sortType}"`);
2470
- if (s.queryFailed) sAttrs.push("queryFailed=\"1\"");
2471
- p.push(`<set ${sAttrs.join(" ")}/>`);
2472
- }
2473
- p.push("</sets>");
2474
- }
2475
- if (hasSF) {
2476
- p.push(`<serverFormats count="${cd.serverFormats.length}">`);
2477
- for (const sf of cd.serverFormats) {
2478
- const sfAttrs = [];
2479
- if (sf.culture) sfAttrs.push(`culture="${escapeXml(sf.culture)}"`);
2480
- if (sf.format) sfAttrs.push(`format="${escapeXml(sf.format)}"`);
2481
- p.push(`<serverFormat ${sfAttrs.join(" ")}/>`);
2482
- }
2483
- p.push("</serverFormats>");
2484
- }
2485
- if (hasQC) {
2486
- p.push(`<queryCache count="${cd.queryCache.length}">`);
2487
- for (const q of cd.queryCache) {
2488
- const qInner = q.tpls && q.tpls.length > 0 ? `<tpls count="${q.tpls.length}">${q.tpls.map((tpl) => tpl.items && tpl.items.length > 0 ? `<tpl>${tpl.items.map((x) => `<x v="${x}"/>`).join("")}</tpl>` : "<tpl/>").join("")}</tpls>` : "";
2489
- if (qInner) p.push(`<query mdx="${escapeXml(q.mdx)}">${qInner}</query>`);
2490
- else p.push(`<query mdx="${escapeXml(q.mdx)}"/>`);
2491
- }
2492
- p.push("</queryCache>");
2493
- }
2494
- p.push("</tupleCache>");
2495
- }
2496
- p.push("</pivotCacheDefinition>");
2497
- return p.join("");
2498
- }
2499
- function stringifyPivotCacheRecords(sourceData) {
2500
- const numericFields = sourceData.fieldNames.map((_, i) => isNumericField(sourceData.records, i));
2501
- const fieldIndexMaps = sourceData.fieldNames.map((_, i) => {
2502
- if (numericFields[i]) return /* @__PURE__ */ new Map();
2503
- const unique = collectUniqueValues(sourceData.records, i);
2504
- const map = /* @__PURE__ */ new Map();
2505
- for (let j = 0; j < unique.length; j++) map.set(String(unique[j]), j);
2506
- return map;
2507
- });
2508
- const p = [];
2509
- p.push(`<pivotCacheRecords xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${sourceData.records.length}">`);
2510
- for (const row of sourceData.records) {
2511
- p.push("<r>");
2512
- for (let i = 0; i < row.length; i++) {
2513
- const val = row[i];
2514
- if (val === null) p.push("<m/>");
2515
- else if (val instanceof Date) p.push(`<d v="${val.toISOString().replace(/\.\d{3}Z$/, "Z")}"/>`);
2516
- else if (numericFields[i]) p.push(`<n v="${val}"/>`);
2517
- else p.push(`<x v="${fieldIndexMaps[i]?.get(String(val)) ?? 0}"/>`);
2518
- }
2519
- p.push("</r>");
2520
- }
2521
- p.push("</pivotCacheRecords>");
2522
- return p.join("");
2523
- }
2524
- //#endregion
2525
- //#region src/parts/table.ts
2526
- const TotalsRowFunction = {
2527
- NONE: "none",
2528
- SUM: "sum",
2529
- MIN: "min",
2530
- MAX: "max",
2531
- AVERAGE: "average",
2532
- COUNT: "count",
2533
- COUNT_NUMS: "countNums",
2534
- STD_DEV: "stdDev",
2535
- VAR: "var",
2536
- CUSTOM: "custom"
2537
- };
2538
- const TableType = {
2539
- WORKSHEET: "worksheet",
2540
- XML: "xml",
2541
- QUERY_TABLE: "queryTable"
2542
- };
2543
- function buildAttrs(attrsMap) {
2544
- const parts = [];
2545
- for (const [k, v] of Object.entries(attrsMap)) {
2546
- if (v === void 0) continue;
2547
- parts.push(` ${k}="${typeof v === "string" ? escapeXml(v) : String(v)}"`);
2548
- }
2549
- return parts.join("");
2550
- }
2551
- const tableDesc = {
2552
- kind: "custom",
2553
- stringify(o, _ctx) {
2554
- const p = [];
2555
- const rootAttrs = {
2556
- id: o.id,
2557
- name: o.name ?? o.displayName,
2558
- displayName: o.displayName,
2559
- ref: o.ref
2560
- };
2561
- if (o.tableType && o.tableType !== "worksheet") rootAttrs.tableType = o.tableType;
2562
- if (o.headerRowCount !== void 0 && o.headerRowCount !== 1) rootAttrs.headerRowCount = o.headerRowCount;
2563
- if (o.totalsRowCount !== void 0 && o.totalsRowCount > 0) rootAttrs.totalsRowCount = o.totalsRowCount;
2564
- if (o.totalsRowShown === false) rootAttrs.totalsRowShown = 0;
2565
- if (o.insertRowShift) rootAttrs.insertRowShift = 1;
2566
- if (o.published) rootAttrs.published = 1;
2567
- if (o.headerRowDxfId !== void 0) rootAttrs.headerRowDxfId = o.headerRowDxfId;
2568
- if (o.dataDxfId !== void 0) rootAttrs.dataDxfId = o.dataDxfId;
2569
- if (o.totalsRowDxfId !== void 0) rootAttrs.totalsRowDxfId = o.totalsRowDxfId;
2570
- if (o.headerRowBorderDxfId !== void 0) rootAttrs.headerRowBorderDxfId = o.headerRowBorderDxfId;
2571
- if (o.tableBorderDxfId !== void 0) rootAttrs.tableBorderDxfId = o.tableBorderDxfId;
2572
- if (o.totalsRowBorderDxfId !== void 0) rootAttrs.totalsRowBorderDxfId = o.totalsRowBorderDxfId;
2573
- if (o.headerRowCellStyle) rootAttrs.headerRowCellStyle = o.headerRowCellStyle;
2574
- if (o.dataCellStyle) rootAttrs.dataCellStyle = o.dataCellStyle;
2575
- if (o.totalsRowCellStyle) rootAttrs.totalsRowCellStyle = o.totalsRowCellStyle;
2576
- p.push(`<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="xr xr2" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:xr2="http://schemas.microsoft.com/office/spreadsheetml/2015/revision2"${buildAttrs(rootAttrs)}>`);
2577
- if (o.autoFilter !== void 0) p.push(`<autoFilter ref="${escapeXml(o.autoFilter)}"/>`);
2578
- p.push(`<tableColumns count="${o.columns.length}">`);
2579
- for (const [i, col] of o.columns.entries()) {
2580
- const colAttrs = {
2581
- id: i + 1,
2582
- name: col.name
2583
- };
2584
- const inner = [];
2585
- if (col.calculatedColumnFormula !== void 0) {
2586
- const fAttrs = col.calculatedColumnFormulaArray ? " array=\"1\"" : "";
2587
- inner.push(`<calculatedColumnFormula${fAttrs}>${escapeXml(col.calculatedColumnFormula)}</calculatedColumnFormula>`);
2588
- }
2589
- if (col.totalsRowFormula !== void 0) {
2590
- const fAttrs = col.totalsRowFormulaArray ? " array=\"1\"" : "";
2591
- inner.push(`<totalsRowFormula${fAttrs}>${escapeXml(col.totalsRowFormula)}</totalsRowFormula>`);
2592
- }
2593
- if (col.totalsRowFunction !== void 0 && col.totalsRowFunction !== TotalsRowFunction.NONE) colAttrs.totalsRowFunction = col.totalsRowFunction;
2594
- if (col.totalsRowLabel !== void 0) colAttrs.totalsRowLabel = col.totalsRowLabel;
2595
- if (col.uniqueName) colAttrs.uniqueName = col.uniqueName;
2596
- if (col.queryTableFieldId !== void 0) colAttrs.queryTableFieldId = col.queryTableFieldId;
2597
- if (col.headerRowDxfId !== void 0) colAttrs.headerRowDxfId = col.headerRowDxfId;
2598
- if (col.dataDxfId !== void 0) colAttrs.dataDxfId = col.dataDxfId;
2599
- if (col.totalsRowDxfId !== void 0) colAttrs.totalsRowDxfId = col.totalsRowDxfId;
2600
- if (col.headerRowCellStyle) colAttrs.headerRowCellStyle = col.headerRowCellStyle;
2601
- if (col.dataCellStyle) colAttrs.dataCellStyle = col.dataCellStyle;
2602
- if (col.totalsRowCellStyle) colAttrs.totalsRowCellStyle = col.totalsRowCellStyle;
2603
- if (inner.length > 0) p.push(`<tableColumn${buildAttrs(colAttrs)}>${inner.join("")}</tableColumn>`);
2604
- else p.push(`<tableColumn${buildAttrs(colAttrs)}/>`);
2605
- }
2606
- p.push("</tableColumns>");
2607
- if (o.style) {
2608
- const s = o.style;
2609
- const styleAttrs = {};
2610
- if (s.name !== void 0) styleAttrs.name = s.name;
2611
- if (s.showFirstColumn) styleAttrs.showFirstColumn = 1;
2612
- if (s.showLastColumn) styleAttrs.showLastColumn = 1;
2613
- if (s.showRowStripes !== false) styleAttrs.showRowStripes = 1;
2614
- if (s.showColumnStripes) styleAttrs.showColumnStripes = 1;
2615
- p.push(`<tableStyleInfo${buildAttrs(styleAttrs)}/>`);
2616
- }
2617
- p.push("</table>");
2618
- return p.join("");
2619
- },
2620
- parse(el, _ctx) {
2621
- const result = {};
2622
- const id = attrNum(el, "id");
2623
- if (id !== void 0) result.id = id;
2624
- if (attr(el, "name")) result.name = attr(el, "name");
2625
- if (attr(el, "displayName")) result.displayName = attr(el, "displayName");
2626
- if (attr(el, "ref")) result.ref = attr(el, "ref");
2627
- const headerRowCount = attrNum(el, "headerRowCount");
2628
- if (headerRowCount !== void 0) result.headerRowCount = headerRowCount;
2629
- const totalsRowCount = attrNum(el, "totalsRowCount");
2630
- if (totalsRowCount !== void 0) result.totalsRowCount = totalsRowCount;
2631
- if (attr(el, "totalsRowShown") === "0") result.totalsRowShown = false;
2632
- if (attr(el, "tableType")) result.tableType = attr(el, "tableType");
2633
- if (attr(el, "insertRowShift") === "1") result.insertRowShift = true;
2634
- if (attr(el, "published") === "1") result.published = true;
2635
- const afEl = findChild(el, "autoFilter");
2636
- if (afEl) result.autoFilter = attr(afEl, "ref") ?? "";
2637
- const colsEl = findChild(el, "tableColumns");
2638
- if (colsEl) {
2639
- const columns = [];
2640
- for (const colEl of colsEl.elements ?? []) {
2641
- if (colEl.name !== "tableColumn") continue;
2642
- const col = {};
2643
- col.name = attr(colEl, "name") ?? "";
2644
- if (attr(colEl, "totalsRowFunction")) col.totalsRowFunction = attr(colEl, "totalsRowFunction");
2645
- if (attr(colEl, "totalsRowLabel")) col.totalsRowLabel = attr(colEl, "totalsRowLabel");
2646
- const ccfEl = findChild(colEl, "calculatedColumnFormula");
2647
- if (ccfEl) {
2648
- col.calculatedColumnFormula = textOf(ccfEl);
2649
- if (attr(ccfEl, "array") === "1") col.calculatedColumnFormulaArray = true;
2650
- }
2651
- const trfEl = findChild(colEl, "totalsRowFormula");
2652
- if (trfEl) {
2653
- col.totalsRowFormula = textOf(trfEl);
2654
- if (attr(trfEl, "array") === "1") col.totalsRowFormulaArray = true;
2655
- }
2656
- if (attr(colEl, "uniqueName")) col.uniqueName = attr(colEl, "uniqueName");
2657
- const qtfId = attrNum(colEl, "queryTableFieldId");
2658
- if (qtfId !== void 0) col.queryTableFieldId = qtfId;
2659
- const hrDxfId = attrNum(colEl, "headerRowDxfId");
2660
- if (hrDxfId !== void 0) col.headerRowDxfId = hrDxfId;
2661
- const dDxfId = attrNum(colEl, "dataDxfId");
2662
- if (dDxfId !== void 0) col.dataDxfId = dDxfId;
2663
- const trDxfId = attrNum(colEl, "totalsRowDxfId");
2664
- if (trDxfId !== void 0) col.totalsRowDxfId = trDxfId;
2665
- if (attr(colEl, "headerRowCellStyle")) col.headerRowCellStyle = attr(colEl, "headerRowCellStyle");
2666
- if (attr(colEl, "dataCellStyle")) col.dataCellStyle = attr(colEl, "dataCellStyle");
2667
- if (attr(colEl, "totalsRowCellStyle")) col.totalsRowCellStyle = attr(colEl, "totalsRowCellStyle");
2668
- columns.push(col);
2669
- }
2670
- result.columns = columns;
2671
- }
2672
- const siEl = findChild(el, "tableStyleInfo");
2673
- if (siEl) {
2674
- const style = {};
2675
- if (attr(siEl, "name")) style.name = attr(siEl, "name");
2676
- if (attr(siEl, "showFirstColumn") === "1") style.showFirstColumn = true;
2677
- if (attr(siEl, "showLastColumn") === "1") style.showLastColumn = true;
2678
- if (attr(siEl, "showRowStripes") === "1") style.showRowStripes = true;
2679
- if (attr(siEl, "showColumnStripes") === "1") style.showColumnStripes = true;
2680
- result.style = style;
2681
- }
2682
- const hrDxfId = attrNum(el, "headerRowDxfId");
2683
- if (hrDxfId !== void 0) result.headerRowDxfId = hrDxfId;
2684
- const dDxfId = attrNum(el, "dataDxfId");
2685
- if (dDxfId !== void 0) result.dataDxfId = dDxfId;
2686
- const trDxfId = attrNum(el, "totalsRowDxfId");
2687
- if (trDxfId !== void 0) result.totalsRowDxfId = trDxfId;
2688
- const hrbDxfId = attrNum(el, "headerRowBorderDxfId");
2689
- if (hrbDxfId !== void 0) result.headerRowBorderDxfId = hrbDxfId;
2690
- const tbDxfId = attrNum(el, "tableBorderDxfId");
2691
- if (tbDxfId !== void 0) result.tableBorderDxfId = tbDxfId;
2692
- const trbDxfId = attrNum(el, "totalsRowBorderDxfId");
2693
- if (trbDxfId !== void 0) result.totalsRowBorderDxfId = trbDxfId;
2694
- if (attr(el, "headerRowCellStyle")) result.headerRowCellStyle = attr(el, "headerRowCellStyle");
2695
- if (attr(el, "dataCellStyle")) result.dataCellStyle = attr(el, "dataCellStyle");
2696
- if (attr(el, "totalsRowCellStyle")) result.totalsRowCellStyle = attr(el, "totalsRowCellStyle");
2697
- return result;
2698
- }
2699
- };
2700
- //#endregion
2701
- //#region src/parts/workbook.ts
2702
- /**
2703
- * Workbook types and descriptor for SpreadsheetML documents.
2704
- *
2705
- * @module
2706
- */
2707
- const workbookDesc = {
2708
- kind: "custom",
2709
- stringify(opts, _ctx) {
2710
- return stringifyWorkbook(opts);
2711
- },
2712
- parse(el, _ctx) {
2713
- const result = {};
2714
- const sheetsEl = findChild(el, "sheets");
2715
- if (sheetsEl) {
2716
- const sheets = [];
2717
- for (const s of sheetsEl.elements ?? []) {
2718
- if (s.name !== "sheet") continue;
2719
- const name = attr(s, "name") ?? "";
2720
- const sheetId = attrNum(s, "sheetId") ?? 0;
2721
- const rId = s.attributes?.["r:id"] ?? "";
2722
- const state = attr(s, "state");
2723
- sheets.push({
2724
- name,
2725
- sheetId,
2726
- rId,
2727
- state
2728
- });
2729
- }
2730
- result.sheets = sheets;
2731
- }
2732
- const pivotCachesEl = findChild(el, "pivotCaches");
2733
- if (pivotCachesEl) {
2734
- const caches = [];
2735
- for (const pc of pivotCachesEl.elements ?? []) {
2736
- if (pc.name !== "pivotCache") continue;
2737
- caches.push({
2738
- cacheId: attrNum(pc, "cacheId") ?? 0,
2739
- rId: pc.attributes?.["r:id"] ?? ""
2740
- });
2741
- }
2742
- result.pivotCaches = caches;
2743
- }
2744
- const protEl = findChild(el, "workbookProtection");
2745
- if (protEl?.attributes) {
2746
- const prot = {};
2747
- if (attr(protEl, "lockStructure") === "1") prot.lockStructure = true;
2748
- if (attr(protEl, "lockWindows") === "1") prot.lockWindows = true;
2749
- if (attr(protEl, "lockRevision") === "1") prot.lockRevision = true;
2750
- if (attr(protEl, "workbookPassword")) prot.workbookPassword = attr(protEl, "workbookPassword");
2751
- if (attr(protEl, "workbookAlgorithmName")) prot.workbookAlgorithmName = attr(protEl, "workbookAlgorithmName");
2752
- if (attr(protEl, "workbookHashValue")) prot.workbookHashValue = attr(protEl, "workbookHashValue");
2753
- if (attr(protEl, "workbookSaltValue")) prot.workbookSaltValue = attr(protEl, "workbookSaltValue");
2754
- if (attr(protEl, "workbookSpinCount")) prot.workbookSpinCount = attrNum(protEl, "workbookSpinCount");
2755
- result.protection = prot;
2756
- }
2757
- const bookViewsEl = findChild(el, "bookViews");
2758
- if (bookViewsEl) {
2759
- const bvEl = findChild(bookViewsEl, "workbookView");
2760
- if (bvEl?.attributes) {
2761
- const bv = {};
2762
- const xw = attrNum(bvEl, "xWindow");
2763
- if (xw !== void 0) bv.xWindow = xw;
2764
- const yw = attrNum(bvEl, "yWindow");
2765
- if (yw !== void 0) bv.yWindow = yw;
2766
- const ww = attrNum(bvEl, "windowWidth");
2767
- if (ww !== void 0) bv.windowWidth = ww;
2768
- const wh = attrNum(bvEl, "windowHeight");
2769
- if (wh !== void 0) bv.windowHeight = wh;
2770
- const at = attrNum(bvEl, "activeTab");
2771
- if (at !== void 0) bv.activeTab = at;
2772
- if (attr(bvEl, "autoFilterDateGrouping") === "0") bv.autoFilterDateGrouping = false;
2773
- const fs = attrNum(bvEl, "firstSheet");
2774
- if (fs !== void 0) bv.firstSheet = fs;
2775
- if (attr(bvEl, "showHorizontalScroll") === "0") bv.showHorizontalScroll = false;
2776
- if (attr(bvEl, "showVerticalScroll") === "0") bv.showVerticalScroll = false;
2777
- if (attr(bvEl, "showSheetTabs") === "0") bv.showSheetTabs = false;
2778
- const tr = attrNum(bvEl, "tabRatio");
2779
- if (tr !== void 0) bv.tabRatio = tr;
2780
- result.bookView = bv;
2781
- }
2782
- }
2783
- const calcPrEl = findChild(el, "calcPr");
2784
- if (calcPrEl?.attributes) {
2785
- const calc = {};
2786
- const calcId = attrNum(calcPrEl, "calcId");
2787
- if (calcId !== void 0) calc.calcId = calcId;
2788
- if (attr(calcPrEl, "calcMode")) calc.calcMode = attr(calcPrEl, "calcMode");
2789
- if (attr(calcPrEl, "fullCalcOnLoad") === "1") calc.fullCalcOnLoad = true;
2790
- if (attr(calcPrEl, "concurrentCalc") === "0") calc.concurrentCalc = false;
2791
- if (attr(calcPrEl, "refMode")) calc.refMode = attr(calcPrEl, "refMode");
2792
- if (attr(calcPrEl, "calcOnSave") === "0") calc.calcOnSave = false;
2793
- if (attr(calcPrEl, "forceFullCalc") === "1") calc.forceFullCalc = true;
2794
- const cmc = attrNum(calcPrEl, "concurrentManualCount");
2795
- if (cmc !== void 0) calc.concurrentManualCount = cmc;
2796
- if (attr(calcPrEl, "iterate") === "1") calc.iterate = true;
2797
- const ic = attrNum(calcPrEl, "iterateCount");
2798
- if (ic !== void 0) calc.iterateCount = ic;
2799
- const id = attrNum(calcPrEl, "iterateDelta");
2800
- if (id !== void 0) calc.iterateDelta = id;
2801
- if (attr(calcPrEl, "fullPrecision") === "0") calc.fullPrecision = false;
2802
- if (attr(calcPrEl, "calcCompleted") === "1") calc.calcCompleted = true;
2803
- result.calcPr = calc;
2804
- }
2805
- const customViewsEl = findChild(el, "customWorkbookViews");
2806
- if (customViewsEl) {
2807
- const views = [];
2808
- for (const v of customViewsEl.elements ?? []) {
2809
- if (v.name !== "customWorkbookView") continue;
2810
- const view = {
2811
- name: attr(v, "name") ?? "",
2812
- guid: attr(v, "guid") ?? "",
2813
- windowWidth: attrNum(v, "windowWidth") ?? 0,
2814
- windowHeight: attrNum(v, "windowHeight") ?? 0,
2815
- activeSheetId: attrNum(v, "activeSheetId") ?? 1
2816
- };
2817
- const xw = attrNum(v, "xWindow");
2818
- if (xw !== void 0) view.xWindow = xw;
2819
- const yw = attrNum(v, "yWindow");
2820
- if (yw !== void 0) view.yWindow = yw;
2821
- if (attr(v, "showFormulaBar") === "0") view.showFormulaBar = false;
2822
- if (attr(v, "showStatusbar") === "0") view.showStatusbar = false;
2823
- if (attr(v, "showHorizontalScroll") === "0") view.showHorizontalScroll = false;
2824
- if (attr(v, "showVerticalScroll") === "0") view.showVerticalScroll = false;
2825
- if (attr(v, "showSheetTabs") === "0") view.showSheetTabs = false;
2826
- const tabRatio = attrNum(v, "tabRatio");
2827
- if (tabRatio !== void 0) view.tabRatio = tabRatio;
2828
- if (attr(v, "includeHiddenRowCol") === "0") view.includeHiddenRowCol = false;
2829
- if (attr(v, "includePrintSettings") === "0") view.includePrintSettings = false;
2830
- if (attr(v, "personalView") === "1") view.personalView = true;
2831
- if (attr(v, "maximized") === "1") view.maximized = true;
2832
- if (attr(v, "minimized") === "1") view.minimized = true;
2833
- if (attr(v, "autoUpdate") === "1") view.autoUpdate = true;
2834
- const mi = attrNum(v, "mergeInterval");
2835
- if (mi !== void 0) view.mergeInterval = mi;
2836
- if (attr(v, "changesSavedWin") === "1") view.changesSavedWin = true;
2837
- if (attr(v, "onlySync") === "1") view.onlySync = true;
2838
- if (attr(v, "showComments")) view.showComments = attr(v, "showComments");
2839
- views.push(view);
2840
- }
2841
- if (views.length > 0) result.customViews = views;
2842
- }
2843
- const fileSharingEl = findChild(el, "fileSharing");
2844
- if (fileSharingEl?.attributes) {
2845
- const fs = {};
2846
- if (attr(fileSharingEl, "readOnlyRecommended") === "1") fs.readOnlyRecommended = true;
2847
- if (attr(fileSharingEl, "userName")) fs.userName = attr(fileSharingEl, "userName");
2848
- if (attr(fileSharingEl, "reservationPassword")) fs.reservationPassword = attr(fileSharingEl, "reservationPassword");
2849
- if (attr(fileSharingEl, "algorithmName")) fs.algorithmName = attr(fileSharingEl, "algorithmName");
2850
- if (attr(fileSharingEl, "hashValue")) fs.hashValue = attr(fileSharingEl, "hashValue");
2851
- if (attr(fileSharingEl, "saltValue")) fs.saltValue = attr(fileSharingEl, "saltValue");
2852
- const sc = attrNum(fileSharingEl, "spinCount");
2853
- if (sc !== void 0) fs.spinCount = sc;
2854
- result.fileSharing = fs;
2855
- }
2856
- const webPublishingEl = findChild(el, "webPublishing");
2857
- if (webPublishingEl?.attributes) {
2858
- const wp = {};
2859
- if (attr(webPublishingEl, "css") === "0") wp.css = false;
2860
- if (attr(webPublishingEl, "thicket") === "0") wp.thicket = false;
2861
- if (attr(webPublishingEl, "longFileNames") === "0") wp.longFileNames = false;
2862
- if (attr(webPublishingEl, "vml") === "1") wp.vml = true;
2863
- if (attr(webPublishingEl, "allowPng") === "1") wp.allowPng = true;
2864
- if (attr(webPublishingEl, "targetScreenSize")) wp.targetScreenSize = attr(webPublishingEl, "targetScreenSize");
2865
- const dpi = attrNum(webPublishingEl, "dpi");
2866
- if (dpi !== void 0) wp.dpi = dpi;
2867
- const codePage = attrNum(webPublishingEl, "codePage");
2868
- if (codePage !== void 0) wp.codePage = codePage;
2869
- if (attr(webPublishingEl, "characterSet")) wp.characterSet = attr(webPublishingEl, "characterSet");
2870
- result.webPublishing = wp;
2871
- }
2872
- const fileRecoveryEl = findChild(el, "fileRecoveryPr");
2873
- if (fileRecoveryEl?.attributes) {
2874
- const frp = {};
2875
- if (attr(fileRecoveryEl, "autoRecover") === "0") frp.autoRecover = false;
2876
- if (attr(fileRecoveryEl, "crashSave") === "1") frp.crashSave = true;
2877
- if (attr(fileRecoveryEl, "dataExtractLoad") === "1") frp.dataExtractLoad = true;
2878
- if (attr(fileRecoveryEl, "repairLoad") === "1") frp.repairLoad = true;
2879
- result.fileRecoveryPr = frp;
2880
- }
2881
- const wbPrEl = findChild(el, "workbookPr");
2882
- if (wbPrEl?.attributes) {
2883
- const wbPr = {};
2884
- if (attr(wbPrEl, "date1904") === "1") wbPr.date1904 = true;
2885
- const dtv = attrNum(wbPrEl, "defaultThemeVersion");
2886
- if (dtv !== void 0) wbPr.defaultThemeVersion = dtv;
2887
- if (attr(wbPrEl, "showObjects")) wbPr.showObjects = attr(wbPrEl, "showObjects");
2888
- if (attr(wbPrEl, "hidePivotFieldList") === "1") wbPr.hidePivotFieldList = true;
2889
- if (attr(wbPrEl, "allowRefreshQuery") === "1") wbPr.allowRefreshQuery = true;
2890
- if (attr(wbPrEl, "filterPrivacy") === "1") wbPr.filterPrivacy = true;
2891
- if (attr(wbPrEl, "backupFile") === "1") wbPr.backupFile = true;
2892
- if (attr(wbPrEl, "codeName")) wbPr.codeName = attr(wbPrEl, "codeName");
2893
- if (attr(wbPrEl, "showBorderUnselectedTables") === "1") wbPr.showBorderUnselectedTables = true;
2894
- if (attr(wbPrEl, "promptedSolutions") === "1") wbPr.promptedSolutions = true;
2895
- if (attr(wbPrEl, "showInkAnnotation") === "0") wbPr.showInkAnnotation = false;
2896
- if (attr(wbPrEl, "saveExternalLinkValues") === "0") wbPr.saveExternalLinkValues = false;
2897
- if (attr(wbPrEl, "updateLinks")) wbPr.updateLinks = attr(wbPrEl, "updateLinks");
2898
- if (attr(wbPrEl, "showPivotChartFilter") === "1") wbPr.showPivotChartFilter = true;
2899
- if (attr(wbPrEl, "publishItems") === "1") wbPr.publishItems = true;
2900
- if (attr(wbPrEl, "checkCompatibility") === "1") wbPr.checkCompatibility = true;
2901
- if (attr(wbPrEl, "autoCompressPictures") === "0") wbPr.autoCompressPictures = false;
2902
- if (attr(wbPrEl, "refreshAllConnections") === "1") wbPr.refreshAllConnections = true;
2903
- result.workbookPr = wbPr;
2904
- }
2905
- const fgEl = findChild(el, "functionGroups");
2906
- if (fgEl) {
2907
- const names = [];
2908
- for (const fg of fgEl.elements ?? []) if (fg.name === "functionGroup" && attr(fg, "name")) names.push(attr(fg, "name"));
2909
- if (names.length > 0) result.functionGroups = names;
2910
- }
2911
- const wpoEl = findChild(el, "webPublishObjects");
2912
- if (wpoEl) {
2913
- const objs = [];
2914
- for (const wo of wpoEl.elements ?? []) {
2915
- if (wo.name !== "webPublishObject") continue;
2916
- const obj = { rId: wo.attributes?.["r:id"] ?? "" };
2917
- if (attr(wo, "destinationFile")) obj.destinationFile = attr(wo, "destinationFile");
2918
- if (attr(wo, "autoRepublish") === "1") obj.autoRepublish = true;
2919
- if (attr(wo, "title")) obj.title = attr(wo, "title");
2920
- if (attr(wo, "sourceObject")) obj.sourceObject = attr(wo, "sourceObject");
2921
- if (attr(wo, "appName")) obj.appName = attr(wo, "appName");
2922
- objs.push(obj);
2923
- }
2924
- if (objs.length > 0) result.webPublishObjects = objs;
2925
- }
2926
- const vtEl = findChild(el, "volTypes");
2927
- if (vtEl) {
2928
- const volTypes = [];
2929
- for (const vt of vtEl.elements ?? []) {
2930
- if (vt.name !== "volType") continue;
2931
- const volType = {};
2932
- const typeVal = attr(vt, "type");
2933
- if (typeVal) volType.type = typeVal;
2934
- const mains = [];
2935
- for (const m of vt.elements ?? []) {
2936
- if (m.name !== "main") continue;
2937
- const main = { first: attr(m, "first") ?? "" };
2938
- const topics = [];
2939
- for (const tp of m.elements ?? []) {
2940
- if (tp.name !== "tp") continue;
2941
- const vEl = findChild(tp, "v");
2942
- const topic = { value: String(vEl?.elements?.[0]?.text ?? "") };
2943
- const tVal = attr(tp, "t");
2944
- if (tVal) topic.valueType = tVal;
2945
- const stps = [];
2946
- const refs = [];
2947
- for (const inner of tp.elements ?? []) {
2948
- if (inner.name === "stp") stps.push(String(inner.elements?.[0]?.text ?? ""));
2949
- if (inner.name === "tr") {
2950
- const ref = {
2951
- reference: attr(inner, "r") ?? "",
2952
- sheetIndex: attrNum(inner, "s") ?? 0
2953
- };
2954
- refs.push(ref);
2955
- }
2956
- }
2957
- if (stps.length > 0) topic.stringTopics = stps;
2958
- if (refs.length > 0) topic.refs = refs;
2959
- topics.push(topic);
2960
- }
2961
- if (topics.length > 0) main.topics = topics;
2962
- mains.push(main);
2963
- }
2964
- if (mains.length > 0) volType.mains = mains;
2965
- volTypes.push(volType);
2966
- }
2967
- if (volTypes.length > 0) result.volTypes = volTypes;
2968
- }
2969
- if (el.attributes?.["conformance"]) result.conformance = attr(el, "conformance");
2970
- return result;
2971
- }
2972
- };
2973
- function stringifyWorkbook(opts) {
2974
- const parts = [`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x15 xr xr6 xr10 xr2" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:xr6="http://schemas.microsoft.com/office/spreadsheetml/2016/revision6" xmlns:xr10="http://schemas.microsoft.com/office/spreadsheetml/2016/revision10" xmlns:xr2="http://schemas.microsoft.com/office/spreadsheetml/2015/revision2"${opts.conformance ? ` conformance="${opts.conformance}"` : ""}>`, "<fileVersion appName=\"xl\" lastEdited=\"7\" lowestEdited=\"6\" rupBuild=\"29929\"/>"];
2975
- if (opts.fileSharing) {
2976
- const fs = opts.fileSharing;
2977
- const fsAttrs = [];
2978
- if (fs.readOnlyRecommended) fsAttrs.push("readOnlyRecommended=\"1\"");
2979
- if (fs.userName) fsAttrs.push(`userName="${escapeXml(fs.userName)}"`);
2980
- if (fs.reservationPassword) {
2981
- fsAttrs.push(`reservationPassword="${escapeXml(fs.reservationPassword)}"`);
2982
- if (fs.hashValue === void 0) {
2983
- const derived = derivePasswordHash(fs.reservationPassword);
2984
- fsAttrs.push(`algorithmName="${escapeXml(derived.algorithmName)}"`);
2985
- fsAttrs.push(`hashValue="${escapeXml(derived.hashValue)}"`);
2986
- fsAttrs.push(`saltValue="${escapeXml(derived.saltValue)}"`);
2987
- fsAttrs.push(`spinCount="${derived.spinCount}"`);
2988
- }
2989
- }
2990
- if (fs.algorithmName) fsAttrs.push(`algorithmName="${escapeXml(fs.algorithmName)}"`);
2991
- if (fs.hashValue) fsAttrs.push(`hashValue="${escapeXml(fs.hashValue)}"`);
2992
- if (fs.saltValue) fsAttrs.push(`saltValue="${escapeXml(fs.saltValue)}"`);
2993
- if (fs.spinCount !== void 0) fsAttrs.push(`spinCount="${fs.spinCount}"`);
2994
- if (fsAttrs.length > 0) parts.push(`<fileSharing ${fsAttrs.join(" ")}/>`);
2995
- }
2996
- if (opts.workbookPr) {
2997
- const wbPr = opts.workbookPr;
2998
- const wbPrAttrs = [];
2999
- if (wbPr.date1904) wbPrAttrs.push("date1904=\"1\"");
3000
- if (wbPr.defaultThemeVersion !== void 0) wbPrAttrs.push(`defaultThemeVersion="${wbPr.defaultThemeVersion}"`);
3001
- if (wbPr.showObjects) wbPrAttrs.push(`showObjects="${escapeXml(wbPr.showObjects)}"`);
3002
- if (wbPr.hidePivotFieldList) wbPrAttrs.push("hidePivotFieldList=\"1\"");
3003
- if (wbPr.allowRefreshQuery) wbPrAttrs.push("allowRefreshQuery=\"1\"");
3004
- if (wbPr.filterPrivacy) wbPrAttrs.push("filterPrivacy=\"1\"");
3005
- if (wbPr.backupFile) wbPrAttrs.push("backupFile=\"1\"");
3006
- if (wbPr.codeName) wbPrAttrs.push(`codeName="${escapeXml(wbPr.codeName)}"`);
3007
- if (wbPr.showBorderUnselectedTables) wbPrAttrs.push("showBorderUnselectedTables=\"1\"");
3008
- if (wbPr.promptedSolutions) wbPrAttrs.push("promptedSolutions=\"1\"");
3009
- if (wbPr.showInkAnnotation === false) wbPrAttrs.push("showInkAnnotation=\"0\"");
3010
- if (wbPr.saveExternalLinkValues === false) wbPrAttrs.push("saveExternalLinkValues=\"0\"");
3011
- if (wbPr.updateLinks) wbPrAttrs.push(`updateLinks="${escapeXml(wbPr.updateLinks)}"`);
3012
- if (wbPr.showPivotChartFilter) wbPrAttrs.push("showPivotChartFilter=\"1\"");
3013
- if (wbPr.publishItems) wbPrAttrs.push("publishItems=\"1\"");
3014
- if (wbPr.checkCompatibility) wbPrAttrs.push("checkCompatibility=\"1\"");
3015
- if (wbPr.autoCompressPictures === false) wbPrAttrs.push("autoCompressPictures=\"0\"");
3016
- if (wbPr.refreshAllConnections) wbPrAttrs.push("refreshAllConnections=\"1\"");
3017
- parts.push(`<workbookPr${wbPrAttrs.length > 0 ? ` ${wbPrAttrs.join(" ")}` : ""}/>`);
3018
- } else parts.push("<workbookPr/>");
3019
- if (opts.protection) {
3020
- const prot = opts.protection;
3021
- const protAttrs = [];
3022
- if (prot.lockStructure) protAttrs.push("lockStructure=\"1\"");
3023
- if (prot.lockWindows) protAttrs.push("lockWindows=\"1\"");
3024
- if (prot.lockRevision) protAttrs.push("lockRevision=\"1\"");
3025
- if (prot.workbookPassword) {
3026
- protAttrs.push(`workbookPassword="${hashPassword(prot.workbookPassword)}"`);
3027
- if (prot.workbookHashValue === void 0) {
3028
- const wbDerived = derivePasswordHash(prot.workbookPassword);
3029
- protAttrs.push(`workbookAlgorithmName="${escapeXml(wbDerived.algorithmName)}"`);
3030
- protAttrs.push(`workbookHashValue="${escapeXml(wbDerived.hashValue)}"`);
3031
- protAttrs.push(`workbookSaltValue="${escapeXml(wbDerived.saltValue)}"`);
3032
- protAttrs.push(`workbookSpinCount="${wbDerived.spinCount}"`);
3033
- }
3034
- }
3035
- if (prot.workbookAlgorithmName) protAttrs.push(`workbookAlgorithmName="${escapeXml(prot.workbookAlgorithmName)}"`);
3036
- if (prot.workbookHashValue) protAttrs.push(`workbookHashValue="${escapeXml(prot.workbookHashValue)}"`);
3037
- if (prot.workbookSaltValue) protAttrs.push(`workbookSaltValue="${escapeXml(prot.workbookSaltValue)}"`);
3038
- if (prot.workbookSpinCount !== void 0) protAttrs.push(`workbookSpinCount="${prot.workbookSpinCount}"`);
3039
- if (prot.revisionsPassword) {
3040
- protAttrs.push(`revisionsPassword="${hashPassword(prot.revisionsPassword)}"`);
3041
- if (prot.revisionsHashValue === void 0) {
3042
- const revDerived = derivePasswordHash(prot.revisionsPassword);
3043
- protAttrs.push(`revisionsAlgorithmName="${escapeXml(revDerived.algorithmName)}"`);
3044
- protAttrs.push(`revisionsHashValue="${escapeXml(revDerived.hashValue)}"`);
3045
- protAttrs.push(`revisionsSaltValue="${escapeXml(revDerived.saltValue)}"`);
3046
- protAttrs.push(`revisionsSpinCount="${revDerived.spinCount}"`);
3047
- }
3048
- }
3049
- if (prot.revisionsAlgorithmName) protAttrs.push(`revisionsAlgorithmName="${escapeXml(prot.revisionsAlgorithmName)}"`);
3050
- if (prot.revisionsHashValue) protAttrs.push(`revisionsHashValue="${escapeXml(prot.revisionsHashValue)}"`);
3051
- if (prot.revisionsSaltValue) protAttrs.push(`revisionsSaltValue="${escapeXml(prot.revisionsSaltValue)}"`);
3052
- if (prot.revisionsSpinCount !== void 0) protAttrs.push(`revisionsSpinCount="${prot.revisionsSpinCount}"`);
3053
- if (prot.workbookPasswordCharacterSet) protAttrs.push(`workbookPasswordCharacterSet="${escapeXml(prot.workbookPasswordCharacterSet)}"`);
3054
- if (prot.revisionsPasswordCharacterSet) protAttrs.push(`revisionsPasswordCharacterSet="${escapeXml(prot.revisionsPasswordCharacterSet)}"`);
3055
- if (protAttrs.length > 0) parts.push(`<workbookProtection ${protAttrs.join(" ")}/>`);
3056
- }
3057
- if (opts.bookView) {
3058
- const bv = opts.bookView;
3059
- const bvAttrs = [];
3060
- if (bv.xWindow !== void 0) bvAttrs.push(`xWindow="${bv.xWindow}"`);
3061
- else bvAttrs.push("xWindow=\"0\"");
3062
- if (bv.yWindow !== void 0) bvAttrs.push(`yWindow="${bv.yWindow}"`);
3063
- else bvAttrs.push("yWindow=\"0\"");
3064
- if (bv.windowWidth !== void 0) bvAttrs.push(`windowWidth="${bv.windowWidth}"`);
3065
- else bvAttrs.push("windowWidth=\"28800\"");
3066
- if (bv.windowHeight !== void 0) bvAttrs.push(`windowHeight="${bv.windowHeight}"`);
3067
- else bvAttrs.push("windowHeight=\"12300\"");
3068
- if (bv.activeTab !== void 0) bvAttrs.push(`activeTab="${bv.activeTab}"`);
3069
- if (bv.autoFilterDateGrouping === false) bvAttrs.push("autoFilterDateGrouping=\"0\"");
3070
- if (bv.firstSheet !== void 0) bvAttrs.push(`firstSheet="${bv.firstSheet}"`);
3071
- if (bv.showHorizontalScroll === false) bvAttrs.push("showHorizontalScroll=\"0\"");
3072
- if (bv.showSheetTabs === false) bvAttrs.push("showSheetTabs=\"0\"");
3073
- if (bv.showVerticalScroll === false) bvAttrs.push("showVerticalScroll=\"0\"");
3074
- if (bv.tabRatio !== void 0) bvAttrs.push(`tabRatio="${bv.tabRatio}"`);
3075
- parts.push(`<bookViews><workbookView ${bvAttrs.join(" ")}/></bookViews>`);
3076
- } else parts.push("<bookViews><workbookView xWindow=\"0\" yWindow=\"0\" windowWidth=\"28800\" windowHeight=\"12300\"/></bookViews>");
3077
- parts.push("<sheets>");
3078
- for (const s of opts.sheets) {
3079
- const stateAttr = s.state && s.state !== "visible" ? ` state="${s.state}"` : "";
3080
- parts.push(`<sheet name="${escapeXml(s.name)}" sheetId="${s.sheetId}" r:id="${s.rId}"${stateAttr}/>`);
3081
- }
3082
- parts.push("</sheets>");
3083
- const functionGroups = opts.functionGroups ?? [];
3084
- if (functionGroups.length > 0) {
3085
- const fgParts = [`<functionGroups builtInGroupCount="16">`];
3086
- for (const name of functionGroups) fgParts.push(`<functionGroup name="${escapeXml(name)}"/>`);
3087
- fgParts.push("</functionGroups>");
3088
- parts.push(fgParts.join(""));
3089
- }
3090
- parts.push("<!--EXTERNAL_REFS-->");
3091
- if (opts.calcPr) {
3092
- const cp = opts.calcPr;
3093
- const cpAttrs = [];
3094
- cpAttrs.push(`calcId="${cp.calcId ?? 191029}"`);
3095
- if (cp.calcMode) cpAttrs.push(`calcMode="${escapeXml(cp.calcMode)}"`);
3096
- if (cp.fullCalcOnLoad) cpAttrs.push("fullCalcOnLoad=\"1\"");
3097
- if (cp.calcOnSave === false) cpAttrs.push("calcOnSave=\"0\"");
3098
- if (cp.forceFullCalc) cpAttrs.push("forceFullCalc=\"1\"");
3099
- if (cp.concurrentCalc === false) cpAttrs.push("concurrentCalc=\"0\"");
3100
- if (cp.concurrentManualCount !== void 0) cpAttrs.push(`concurrentManualCount="${cp.concurrentManualCount}"`);
3101
- if (cp.iterate) cpAttrs.push("iterate=\"1\"");
3102
- if (cp.iterateCount !== void 0) cpAttrs.push(`iterateCount="${cp.iterateCount}"`);
3103
- if (cp.iterateDelta !== void 0) cpAttrs.push(`iterateDelta="${cp.iterateDelta}"`);
3104
- if (cp.refMode) cpAttrs.push(`refMode="${escapeXml(cp.refMode)}"`);
3105
- if (cp.fullPrecision === false) cpAttrs.push("fullPrecision=\"0\"");
3106
- if (cp.calcCompleted) cpAttrs.push("calcCompleted=\"1\"");
3107
- parts.push(`<calcPr ${cpAttrs.join(" ")}/>`);
3108
- } else parts.push("<calcPr calcId=\"191029\" fullCalcOnLoad=\"1\"/>");
3109
- if (opts.customViews && opts.customViews.length > 0) {
3110
- parts.push("<customWorkbookViews>");
3111
- for (const v of opts.customViews) {
3112
- const vAttrs = [
3113
- `name="${escapeXml(v.name)}"`,
3114
- `guid="${escapeXml(v.guid)}"`,
3115
- `windowWidth="${v.windowWidth}"`,
3116
- `windowHeight="${v.windowHeight}"`,
3117
- `activeSheetId="${v.activeSheetId}"`
3118
- ];
3119
- if (v.xWindow !== void 0) vAttrs.push(`xWindow="${v.xWindow}"`);
3120
- if (v.yWindow !== void 0) vAttrs.push(`yWindow="${v.yWindow}"`);
3121
- if (v.showFormulaBar === false) vAttrs.push("showFormulaBar=\"0\"");
3122
- if (v.showStatusbar === false) vAttrs.push("showStatusbar=\"0\"");
3123
- if (v.showHorizontalScroll === false) vAttrs.push("showHorizontalScroll=\"0\"");
3124
- if (v.showVerticalScroll === false) vAttrs.push("showVerticalScroll=\"0\"");
3125
- if (v.showSheetTabs === false) vAttrs.push("showSheetTabs=\"0\"");
3126
- if (v.tabRatio !== void 0) vAttrs.push(`tabRatio="${v.tabRatio}"`);
3127
- if (v.includeHiddenRowCol === false) vAttrs.push("includeHiddenRowCol=\"0\"");
3128
- if (v.includePrintSettings === false) vAttrs.push("includePrintSettings=\"0\"");
3129
- if (v.personalView) vAttrs.push("personalView=\"1\"");
3130
- if (v.maximized) vAttrs.push("maximized=\"1\"");
3131
- if (v.minimized) vAttrs.push("minimized=\"1\"");
3132
- if (v.autoUpdate) vAttrs.push("autoUpdate=\"1\"");
3133
- if (v.mergeInterval !== void 0) vAttrs.push(`mergeInterval="${v.mergeInterval}"`);
3134
- if (v.changesSavedWin) vAttrs.push("changesSavedWin=\"1\"");
3135
- if (v.onlySync) vAttrs.push("onlySync=\"1\"");
3136
- if (v.showComments) vAttrs.push(`showComments="${escapeXml(v.showComments)}"`);
3137
- parts.push(`<customWorkbookView ${vAttrs.join(" ")}/>`);
3138
- }
3139
- parts.push("</customWorkbookViews>");
3140
- }
3141
- const pivotCaches = opts.pivotCaches ?? [];
3142
- if (pivotCaches.length > 0) {
3143
- parts.push("<pivotCaches>");
3144
- for (const pc of pivotCaches) parts.push(`<pivotCache cacheId="${pc.cacheId}" r:id="${pc.rId}"/>`);
3145
- parts.push("</pivotCaches>");
3146
- }
3147
- if (opts.webPublishing) {
3148
- const wp = opts.webPublishing;
3149
- const wpAttrs = [];
3150
- if (wp.css === false) wpAttrs.push("css=\"0\"");
3151
- if (wp.thicket === false) wpAttrs.push("thicket=\"0\"");
3152
- if (wp.longFileNames === false) wpAttrs.push("longFileNames=\"0\"");
3153
- if (wp.vml) wpAttrs.push("vml=\"1\"");
3154
- if (wp.allowPng) wpAttrs.push("allowPng=\"1\"");
3155
- if (wp.targetScreenSize && wp.targetScreenSize !== "800x600") wpAttrs.push(`targetScreenSize="${wp.targetScreenSize}"`);
3156
- if (wp.dpi !== void 0 && wp.dpi !== 96) wpAttrs.push(`dpi="${wp.dpi}"`);
3157
- if (wp.codePage !== void 0) wpAttrs.push(`codePage="${wp.codePage}"`);
3158
- if (wp.characterSet) wpAttrs.push(`characterSet="${escapeXml(wp.characterSet)}"`);
3159
- parts.push(`<webPublishing ${wpAttrs.join(" ")}/>`);
3160
- }
3161
- if (opts.fileRecoveryPr) {
3162
- const frp = opts.fileRecoveryPr;
3163
- const frpAttrs = [];
3164
- if (frp.autoRecover === false) frpAttrs.push("autoRecover=\"0\"");
3165
- if (frp.crashSave) frpAttrs.push("crashSave=\"1\"");
3166
- if (frp.dataExtractLoad) frpAttrs.push("dataExtractLoad=\"1\"");
3167
- if (frp.repairLoad) frpAttrs.push("repairLoad=\"1\"");
3168
- if (frpAttrs.length > 0) parts.push(`<fileRecoveryPr ${frpAttrs.join(" ")}/>`);
3169
- }
3170
- if (opts.webPublishObjects && opts.webPublishObjects.length > 0) {
3171
- const wpoParts = [`<webPublishObjects count="${opts.webPublishObjects.length}">`];
3172
- for (const wpo of opts.webPublishObjects) {
3173
- const wpoAttrs = [`r:id="${escapeXml(wpo.rId)}"`];
3174
- if (wpo.destinationFile) wpoAttrs.push(`destinationFile="${escapeXml(wpo.destinationFile)}"`);
3175
- if (wpo.autoRepublish) wpoAttrs.push("autoRepublish=\"1\"");
3176
- if (wpo.title) wpoAttrs.push(`title="${escapeXml(wpo.title)}"`);
3177
- if (wpo.sourceObject) wpoAttrs.push(`sourceObject="${escapeXml(wpo.sourceObject)}"`);
3178
- wpoParts.push(`<webPublishObject ${wpoAttrs.join(" ")}/>`);
3179
- }
3180
- wpoParts.push("</webPublishObjects>");
3181
- parts.push(wpoParts.join(""));
3182
- }
3183
- if (opts.volTypes && opts.volTypes.length > 0) {
3184
- const vtParts = [`<volTypes count="${opts.volTypes.length}">`];
3185
- for (const vt of opts.volTypes) {
3186
- const vtType = vt.type ?? "realTimeData";
3187
- const mains = vt.mains ?? [];
3188
- if (mains.length > 0) {
3189
- const mainParts = [];
3190
- for (const m of mains) {
3191
- const tpParts = [];
3192
- for (const topic of m.topics ?? []) {
3193
- const tpInner = [`<v>${escapeXml(topic.value)}</v>`];
3194
- for (const stp of topic.stringTopics ?? []) tpInner.push(`<stp>${escapeXml(stp)}</stp>`);
3195
- for (const tr of topic.refs ?? []) tpInner.push(`<tr r="${escapeXml(tr.reference)}" s="${tr.sheetIndex}"/>`);
3196
- const tpAttr = topic.valueType && topic.valueType !== "n" ? ` t="${escapeXml(topic.valueType)}"` : "";
3197
- tpParts.push(`<tp${tpAttr}>${tpInner.join("")}</tp>`);
3198
- }
3199
- mainParts.push(`<main first="${escapeXml(m.first)}">${tpParts.join("")}</main>`);
3200
- }
3201
- vtParts.push(`<volType type="${vtType}">${mainParts.join("")}</volType>`);
3202
- } else vtParts.push(`<volType type="${vtType}"/>`);
3203
- }
3204
- vtParts.push("</volTypes>");
3205
- parts.push(vtParts.join(""));
3206
- }
3207
- parts.push("</workbook>");
3208
- return parts.join("");
3209
- }
3210
- /** Generate tableParts XML fragment for embedding in a worksheet. */
3211
- function buildTablePartsXml(tableParts) {
3212
- if (tableParts.length === 0) return "";
3213
- const p = [`<tableParts count="${tableParts.length}">`];
3214
- for (const tp of tableParts) p.push(`<tablePart r:id="${tp.rId}"/>`);
3215
- p.push("</tableParts>");
3216
- return p.join("");
3217
- }
3218
- /** Generate externalReferences XML fragment for embedding in the workbook. */
3219
- function buildExternalReferencesXml(refs) {
3220
- if (refs.length === 0) return "";
3221
- const p = ["<externalReferences>"];
3222
- for (const ref of refs) p.push(`<externalReference r:id="${ref.rId}"/>`);
3223
- p.push("</externalReferences>");
3224
- return p.join("");
3225
- }
3226
- /** Legacy Excel password hash (XOR-based) */
3227
- function hashPassword(password) {
3228
- let hash = 0;
3229
- for (let i = 0; i < password.length; i++) {
3230
- const c = password.charCodeAt(i);
3231
- hash = (hash >> 14 & 1) + (hash << 1 & 32767);
3232
- hash ^= c;
3233
- hash = hash & 16384 ? hash ^ 1 : hash;
3234
- }
3235
- hash = (hash >> 14 & 1) + (hash << 1 & 32767);
3236
- hash = (hash >> 14 & 1) + (hash << 1 & 32767);
3237
- hash ^= password.length;
3238
- return hash.toString(16).toUpperCase().padStart(4, "0");
3239
- }
3240
- //#endregion
3241
- //#region src/parts/revision-log.ts
3242
- const S_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
3243
- const R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
3244
- function stringifyHeader(h) {
3245
- const sheetIds = h.sheetIds.map((id) => `<sheetId val="${id}"/>`).join("");
3246
- const reviewedXml = h.reviewed && h.reviewed.length > 0 ? `<reviewedList count="${h.reviewed.length}">${h.reviewed.map((r) => `<reviewed rId="${r}"/>`).join("")}</reviewedList>` : "";
3247
- let attrs = ` guid="${escapeXml(h.guid)}" dateTime="${escapeXml(h.dateTime)}" maxSheetId="${h.maxSheetId}" userName="${escapeXml(h.userName)}" r:id="${escapeXml(h.rId)}"`;
3248
- if (h.minRId !== void 0) attrs += ` minRId="${h.minRId}"`;
3249
- if (h.maxRId !== void 0) attrs += ` maxRId="${h.maxRId}"`;
3250
- return `<header${attrs}><sheetIdMap count="${h.sheetIds.length}">${sheetIds}</sheetIdMap>${reviewedXml}</header>`;
3251
- }
3252
- function parseHeader(el) {
3253
- const result = {
3254
- guid: attr(el, "guid") ?? "",
3255
- dateTime: attr(el, "dateTime") ?? "",
3256
- userName: attr(el, "userName") ?? "",
3257
- rId: String(el.attributes?.["r:id"] ?? el.attributes?.["id"] ?? ""),
3258
- maxSheetId: Number(attr(el, "maxSheetId") ?? "0"),
3259
- sheetIds: children(findChild(el, "sheetIdMap"), "sheetId").map((s) => Number(attr(s, "val") ?? "0"))
3260
- };
3261
- const reviewedList = findChild(el, "reviewedList");
3262
- if (reviewedList) {
3263
- const reviewed = children(reviewedList, "reviewed").map((r) => Number(attr(r, "rId") ?? "0"));
3264
- if (reviewed.length > 0) result.reviewed = reviewed;
3265
- }
3266
- const minRId = attr(el, "minRId");
3267
- if (minRId !== void 0) result.minRId = Number(minRId);
3268
- const maxRId = attr(el, "maxRId");
3269
- if (maxRId !== void 0) result.maxRId = Number(maxRId);
3270
- return result;
3271
- }
3272
- const revisionHeadersDesc = {
3273
- kind: "custom",
3274
- stringify(opts, _ctx) {
3275
- if (opts.headers.length === 0) return void 0;
3276
- let attrs = ` xmlns="${S_NS}" xmlns:r="${R_NS}" guid="${escapeXml(opts.guid)}"`;
3277
- if (opts.lastGuid) attrs += ` lastGuid="${escapeXml(opts.lastGuid)}"`;
3278
- if (opts.shared !== void 0) attrs += ` shared="${opts.shared ? 1 : 0}"`;
3279
- if (opts.diskRevisions !== void 0) attrs += ` diskRevisions="${opts.diskRevisions ? 1 : 0}"`;
3280
- if (opts.history !== void 0) attrs += ` history="${opts.history ? 1 : 0}"`;
3281
- if (opts.trackRevisions !== void 0) attrs += ` trackRevisions="${opts.trackRevisions ? 1 : 0}"`;
3282
- if (opts.exclusive !== void 0) attrs += ` exclusive="${opts.exclusive ? 1 : 0}"`;
3283
- if (opts.revisionId !== void 0) attrs += ` revisionId="${opts.revisionId}"`;
3284
- if (opts.version !== void 0) attrs += ` version="${opts.version}"`;
3285
- if (opts.keepChangeHistory !== void 0) attrs += ` keepChangeHistory="${opts.keepChangeHistory ? 1 : 0}"`;
3286
- if (opts.protected !== void 0) attrs += ` protected="${opts.protected ? 1 : 0}"`;
3287
- if (opts.preserveHistory !== void 0) attrs += ` preserveHistory="${opts.preserveHistory}"`;
3288
- return `<headers${attrs}>${opts.headers.map(stringifyHeader).join("")}</headers>`;
3289
- },
3290
- parse(el, _ctx) {
3291
- const result = {
3292
- guid: attr(el, "guid") ?? "",
3293
- headers: children(el, "header").map(parseHeader)
3294
- };
3295
- const lastGuid = attr(el, "lastGuid");
3296
- if (lastGuid !== void 0) result.lastGuid = lastGuid;
3297
- readBool(el, "shared", (v) => result.shared = v);
3298
- readBool(el, "diskRevisions", (v) => result.diskRevisions = v);
3299
- readBool(el, "history", (v) => result.history = v);
3300
- readBool(el, "trackRevisions", (v) => result.trackRevisions = v);
3301
- readBool(el, "exclusive", (v) => result.exclusive = v);
3302
- readNum(el, "revisionId", (v) => result.revisionId = v);
3303
- readNum(el, "version", (v) => result.version = v);
3304
- readBool(el, "keepChangeHistory", (v) => result.keepChangeHistory = v);
3305
- readBool(el, "protected", (v) => result.protected = v);
3306
- readNum(el, "preserveHistory", (v) => result.preserveHistory = v);
3307
- return result;
3308
- }
3309
- };
3310
- const usersDesc = {
3311
- kind: "custom",
3312
- stringify(opts, _ctx) {
3313
- if (!opts.users || opts.users.length === 0) return void 0;
3314
- const users = opts.users.map((u) => `<userInfo guid="${escapeXml(u.guid)}" name="${escapeXml(u.name)}" id="${u.id}" dateTime="${escapeXml(u.dateTime)}"/>`).join("");
3315
- return `<users xmlns="${S_NS}" count="${opts.users.length}">${users}</users>`;
3316
- },
3317
- parse(el, _ctx) {
3318
- const users = children(el, "userInfo").map((u) => ({
3319
- guid: attr(u, "guid") ?? "",
3320
- name: attr(u, "name") ?? "",
3321
- id: Number(attr(u, "id") ?? "0"),
3322
- dateTime: attr(u, "dateTime") ?? ""
3323
- }));
3324
- const result = {};
3325
- if (users.length > 0) result.users = users;
3326
- return result;
3327
- }
3328
- };
3329
- function agRevData(data) {
3330
- let s = ` rId="${data.rId}"`;
3331
- if (data.undo) s += ` ua="1"`;
3332
- if (data.rejected) s += ` ra="1"`;
3333
- return s;
3334
- }
3335
- function stringifyEntry(entry) {
3336
- switch (entry.type) {
3337
- case "rowColumn": {
3338
- const d = entry.data;
3339
- let a = agRevData(d) + ` sId="${d.sheetId}" ref="${escapeXml(d.ref)}" action="${d.action}"`;
3340
- if (d.endOfList) a += ` eol="1"`;
3341
- if (d.edge) a += ` edge="1"`;
3342
- return `<rrc${a}>${d.childrenXml ?? ""}</rrc>`;
3343
- }
3344
- case "move": {
3345
- const d = entry.data;
3346
- let a = agRevData(d) + ` sheetId="${d.sheetId}" source="${escapeXml(d.source)}" destination="${escapeXml(d.destination)}"`;
3347
- if (d.sourceSheetId !== void 0) a += ` sourceSheetId="${d.sourceSheetId}"`;
3348
- return `<rm${a}>${d.childrenXml ?? ""}</rm>`;
3349
- }
3350
- case "customView": {
3351
- const d = entry.data;
3352
- return `<rcv guid="${escapeXml(d.guid)}" action="${d.action}"/>`;
3353
- }
3354
- case "sheetRename": {
3355
- const d = entry.data;
3356
- return `<rsnm${agRevData(d)} sheetId="${d.sheetId}" oldName="${escapeXml(d.oldName)}" newName="${escapeXml(d.newName)}"/>`;
3357
- }
3358
- case "insertSheet": {
3359
- const d = entry.data;
3360
- return `<ris${agRevData(d)} sheetId="${d.sheetId}" name="${escapeXml(d.name)}" sheetPosition="${d.sheetPosition}"/>`;
3361
- }
3362
- case "cellChange": {
3363
- const d = entry.data;
3364
- let a = agRevData(d) + ` sId="${d.sheetId}"`;
3365
- if (d.hasOldDxf) a += ` odxf="1"`;
3366
- if (d.xfDxf) a += ` xfDxf="1"`;
3367
- if (d.style) a += ` s="1"`;
3368
- if (d.hasDxf) a += ` dxf="1"`;
3369
- if (d.numFmtId !== void 0) a += ` numFmtId="${d.numFmtId}"`;
3370
- if (d.quotePrefix) a += ` quotePrefix="1"`;
3371
- if (d.oldQuotePrefix) a += ` oldQuotePrefix="1"`;
3372
- if (d.phonetic) a += ` ph="1"`;
3373
- if (d.oldPhonetic) a += ` oldPh="1"`;
3374
- if (d.endOfListFormulaUpdate) a += ` endOfListFormulaUpdate="1"`;
3375
- const children = [
3376
- d.oldCellXml ?? "",
3377
- d.newCellXml,
3378
- d.oldDxfXml ?? "",
3379
- d.newDxfXml ?? ""
3380
- ].filter(Boolean).join("");
3381
- return `<rcc${a}>${children}</rcc>`;
3382
- }
3383
- case "formatting": {
3384
- const d = entry.data;
3385
- let a = ` sheetId="${d.sheetId}" sqref="${escapeXml(d.sqref)}"`;
3386
- if (d.xfDxf) a += ` xfDxf="1"`;
3387
- if (d.style) a += ` s="1"`;
3388
- if (d.start !== void 0) a += ` start="${d.start}"`;
3389
- if (d.length !== void 0) a += ` length="${d.length}"`;
3390
- return `<rfmt${a}>${d.dxfXml ?? ""}</rfmt>`;
3391
- }
3392
- case "autoFormatting": {
3393
- const d = entry.data;
3394
- return `<raf sheetId="${d.sheetId}" ref="${escapeXml(d.ref)}"${d.autoFormatXml ?? ""}/>`;
3395
- }
3396
- case "definedName": {
3397
- const d = entry.data;
3398
- let a = agRevData(d) + ` name="${escapeXml(d.name)}"`;
3399
- if (d.localSheetId !== void 0) a += ` localSheetId="${d.localSheetId}"`;
3400
- if (d.customView) a += ` customView="1"`;
3401
- if (d.function) a += ` function="1"`;
3402
- if (d.oldFunction) a += ` oldFunction="1"`;
3403
- if (d.functionGroupId !== void 0) a += ` functionGroupId="${d.functionGroupId}"`;
3404
- if (d.oldFunctionGroupId !== void 0) a += ` oldFunctionGroupId="${d.oldFunctionGroupId}"`;
3405
- if (d.shortcutKey !== void 0) a += ` shortcutKey="${d.shortcutKey}"`;
3406
- if (d.oldShortcutKey !== void 0) a += ` oldShortcutKey="${d.oldShortcutKey}"`;
3407
- if (d.hidden) a += ` hidden="1"`;
3408
- if (d.oldHidden) a += ` oldHidden="1"`;
3409
- const xstring = (v, attr) => v !== void 0 ? ` ${attr}="${escapeXml(v)}"` : "";
3410
- a += xstring(d.customMenu, "customMenu") + xstring(d.oldCustomMenu, "oldCustomMenu");
3411
- a += xstring(d.description, "description") + xstring(d.oldDescription, "oldDescription");
3412
- a += xstring(d.help, "help") + xstring(d.oldHelp, "oldHelp");
3413
- a += xstring(d.statusBar, "statusBar") + xstring(d.oldStatusBar, "oldStatusBar");
3414
- a += xstring(d.comment, "comment") + xstring(d.oldComment, "oldComment");
3415
- const children = [d.formula !== void 0 ? `<formula>${escapeXml(d.formula)}</formula>` : "", d.oldFormula !== void 0 ? `<oldFormula>${escapeXml(d.oldFormula)}</oldFormula>` : ""].filter(Boolean).join("");
3416
- return `<rdn${a}>${children}</rdn>`;
3417
- }
3418
- case "comment": {
3419
- const d = entry.data;
3420
- let a = ` sheetId="${d.sheetId}" cell="${escapeXml(d.cell)}" guid="${escapeXml(d.guid)}" action="${d.action ?? "add"}" author="${escapeXml(d.author)}"`;
3421
- if (d.alwaysShow) a += ` alwaysShow="1"`;
3422
- if (d.old) a += ` old="1"`;
3423
- if (d.hiddenRow) a += ` hiddenRow="1"`;
3424
- if (d.hiddenColumn) a += ` hiddenColumn="1"`;
3425
- if (d.oldLength !== void 0) a += ` oldLength="${d.oldLength}"`;
3426
- if (d.newLength !== void 0) a += ` newLength="${d.newLength}"`;
3427
- return `<rcmt${a}/>`;
3428
- }
3429
- case "queryTableField": {
3430
- const d = entry.data;
3431
- return `<rqt sheetId="${d.sheetId}" ref="${escapeXml(d.ref)}" fieldId="${d.fieldId}"/>`;
3432
- }
3433
- case "conflict": {
3434
- const d = entry.data;
3435
- let a = agRevData(d);
3436
- if (d.sheetId !== void 0) a += ` sheetId="${d.sheetId}"`;
3437
- return `<rcft${a}/>`;
3438
- }
3439
- }
3440
- }
3441
- /** Serializes an element's children back to a raw XML string (for rawXml passthrough). */
3442
- function childrenToXml(el) {
3443
- if (!el || !el.elements) return "";
3444
- return el.elements.filter((c) => c.type === "element").map((c) => elementToXml(c)).join("");
3445
- }
3446
- function elementToXml(el) {
3447
- const attrStr = Object.entries(el.attributes ?? {}).map(([k, v]) => ` ${k}="${escapeXml(String(v))}"`).join("");
3448
- const inner = el.elements ? el.elements.map((c) => {
3449
- if (c.type === "text") return escapeXml(textOf({ elements: [c] }) ?? "");
3450
- if (c.type === "element") return elementToXml(c);
3451
- return "";
3452
- }).join("") : "";
3453
- return `<${el.name}${attrStr}>${inner}</${el.name}>`;
3454
- }
3455
- /** Returns the first element child of a node as raw XML string. */
3456
- function firstChildXml(el, name) {
3457
- const child = findChild(el ?? void 0, name);
3458
- return child ? elementToXml(child) : void 0;
3459
- }
3460
- function parseBool(el, name) {
3461
- const v = attr(el, name);
3462
- if (v === void 0) return void 0;
3463
- return v === "1" || v === "true";
3464
- }
3465
- function parseEntry(el) {
3466
- switch (el.name) {
3467
- case "rrc": {
3468
- const d = {
3469
- rId: Number(attr(el, "rId") ?? "0"),
3470
- sheetId: Number(attr(el, "sId") ?? "0"),
3471
- ref: attr(el, "ref") ?? "",
3472
- action: attr(el, "action") ?? "insertRow"
3473
- };
3474
- const endOfList = parseBool(el, "eol");
3475
- if (endOfList) d.endOfList = endOfList;
3476
- const edge = parseBool(el, "edge");
3477
- if (edge) d.edge = edge;
3478
- const undo = parseBool(el, "ua");
3479
- if (undo) d.undo = undo;
3480
- const rejected = parseBool(el, "ra");
3481
- if (rejected) d.rejected = rejected;
3482
- const childrenXml = childrenToXml(el);
3483
- if (childrenXml) d.childrenXml = childrenXml;
3484
- return {
3485
- type: "rowColumn",
3486
- data: d
3487
- };
3488
- }
3489
- case "rm": {
3490
- const d = {
3491
- rId: Number(attr(el, "rId") ?? "0"),
3492
- sheetId: Number(attr(el, "sheetId") ?? "0"),
3493
- source: attr(el, "source") ?? "",
3494
- destination: attr(el, "destination") ?? ""
3495
- };
3496
- const sourceSheetId = attr(el, "sourceSheetId");
3497
- if (sourceSheetId !== void 0) d.sourceSheetId = Number(sourceSheetId);
3498
- const undo = parseBool(el, "ua");
3499
- if (undo) d.undo = undo;
3500
- const rejected = parseBool(el, "ra");
3501
- if (rejected) d.rejected = rejected;
3502
- const childrenXml = childrenToXml(el);
3503
- if (childrenXml) d.childrenXml = childrenXml;
3504
- return {
3505
- type: "move",
3506
- data: d
3507
- };
3508
- }
3509
- case "rcv": return {
3510
- type: "customView",
3511
- data: {
3512
- guid: attr(el, "guid") ?? "",
3513
- action: attr(el, "action") ?? "add"
3514
- }
3515
- };
3516
- case "rsnm": {
3517
- const d = {
3518
- rId: Number(attr(el, "rId") ?? "0"),
3519
- sheetId: Number(attr(el, "sheetId") ?? "0"),
3520
- oldName: attr(el, "oldName") ?? "",
3521
- newName: attr(el, "newName") ?? ""
3522
- };
3523
- const undo = parseBool(el, "ua");
3524
- if (undo) d.undo = undo;
3525
- const rejected = parseBool(el, "ra");
3526
- if (rejected) d.rejected = rejected;
3527
- return {
3528
- type: "sheetRename",
3529
- data: d
3530
- };
3531
- }
3532
- case "ris": {
3533
- const d = {
3534
- rId: Number(attr(el, "rId") ?? "0"),
3535
- sheetId: Number(attr(el, "sheetId") ?? "0"),
3536
- name: attr(el, "name") ?? "",
3537
- sheetPosition: Number(attr(el, "sheetPosition") ?? "0")
3538
- };
3539
- const undo = parseBool(el, "ua");
3540
- if (undo) d.undo = undo;
3541
- const rejected = parseBool(el, "ra");
3542
- if (rejected) d.rejected = rejected;
3543
- return {
3544
- type: "insertSheet",
3545
- data: d
3546
- };
3547
- }
3548
- case "rcc": {
3549
- const d = {
3550
- rId: Number(attr(el, "rId") ?? "0"),
3551
- sheetId: Number(attr(el, "sId") ?? "0"),
3552
- newCellXml: firstChildXml(el, "nc") ?? ""
3553
- };
3554
- const hasOldDxf = parseBool(el, "odxf");
3555
- if (hasOldDxf) d.hasOldDxf = hasOldDxf;
3556
- const xfDxf = parseBool(el, "xfDxf");
3557
- if (xfDxf) d.xfDxf = xfDxf;
3558
- const style = parseBool(el, "s");
3559
- if (style) d.style = style;
3560
- const hasDxf = parseBool(el, "dxf");
3561
- if (hasDxf) d.hasDxf = hasDxf;
3562
- const numFmtId = attr(el, "numFmtId");
3563
- if (numFmtId !== void 0) d.numFmtId = Number(numFmtId);
3564
- const quotePrefix = parseBool(el, "quotePrefix");
3565
- if (quotePrefix) d.quotePrefix = quotePrefix;
3566
- const oldQuotePrefix = parseBool(el, "oldQuotePrefix");
3567
- if (oldQuotePrefix) d.oldQuotePrefix = oldQuotePrefix;
3568
- const phonetic = parseBool(el, "ph");
3569
- if (phonetic) d.phonetic = phonetic;
3570
- const oldPhonetic = parseBool(el, "oldPh");
3571
- if (oldPhonetic) d.oldPhonetic = oldPhonetic;
3572
- const endOfList = parseBool(el, "endOfListFormulaUpdate");
3573
- if (endOfList) d.endOfListFormulaUpdate = endOfList;
3574
- const undo = parseBool(el, "ua");
3575
- if (undo) d.undo = undo;
3576
- const rejected = parseBool(el, "ra");
3577
- if (rejected) d.rejected = rejected;
3578
- const oc = firstChildXml(el, "oc");
3579
- if (oc) d.oldCellXml = oc;
3580
- const odxf = firstChildXml(el, "odxf");
3581
- if (odxf) d.oldDxfXml = odxf;
3582
- const ndxf = firstChildXml(el, "ndxf");
3583
- if (ndxf) d.newDxfXml = ndxf;
3584
- return {
3585
- type: "cellChange",
3586
- data: d
3587
- };
3588
- }
3589
- case "rfmt": {
3590
- const d = {
3591
- sheetId: Number(attr(el, "sheetId") ?? "0"),
3592
- sqref: attr(el, "sqref") ?? ""
3593
- };
3594
- const xfDxf = parseBool(el, "xfDxf");
3595
- if (xfDxf) d.xfDxf = xfDxf;
3596
- const style = parseBool(el, "s");
3597
- if (style) d.style = style;
3598
- const start = attr(el, "start");
3599
- if (start !== void 0) d.start = Number(start);
3600
- const length = attr(el, "length");
3601
- if (length !== void 0) d.length = Number(length);
3602
- const dxfXml = firstChildXml(el, "dxf");
3603
- if (dxfXml) d.dxfXml = dxfXml;
3604
- return {
3605
- type: "formatting",
3606
- data: d
3607
- };
3608
- }
3609
- case "raf": {
3610
- const d = {
3611
- sheetId: Number(attr(el, "sheetId") ?? "0"),
3612
- ref: attr(el, "ref") ?? ""
3613
- };
3614
- const autoAttrs = Object.entries(el.attributes ?? {}).filter(([k]) => k !== "sheetId" && k !== "ref").map(([k, v]) => ` ${k}="${escapeXml(String(v))}"`).join("");
3615
- if (autoAttrs) d.autoFormatXml = autoAttrs;
3616
- return {
3617
- type: "autoFormatting",
3618
- data: d
3619
- };
3620
- }
3621
- case "rdn": {
3622
- const d = {
3623
- rId: Number(attr(el, "rId") ?? "0"),
3624
- name: attr(el, "name") ?? ""
3625
- };
3626
- const localSheetId = attr(el, "localSheetId");
3627
- if (localSheetId !== void 0) d.localSheetId = Number(localSheetId);
3628
- readBool(el, "customView", (v) => d.customView = v);
3629
- readBool(el, "function", (v) => d.function = v);
3630
- readBool(el, "oldFunction", (v) => d.oldFunction = v);
3631
- readNum(el, "functionGroupId", (v) => d.functionGroupId = v);
3632
- readNum(el, "oldFunctionGroupId", (v) => d.oldFunctionGroupId = v);
3633
- readNum(el, "shortcutKey", (v) => d.shortcutKey = v);
3634
- readNum(el, "oldShortcutKey", (v) => d.oldShortcutKey = v);
3635
- readBool(el, "hidden", (v) => d.hidden = v);
3636
- readBool(el, "oldHidden", (v) => d.oldHidden = v);
3637
- readStr(el, "customMenu", (v) => d.customMenu = v);
3638
- readStr(el, "oldCustomMenu", (v) => d.oldCustomMenu = v);
3639
- readStr(el, "description", (v) => d.description = v);
3640
- readStr(el, "oldDescription", (v) => d.oldDescription = v);
3641
- readStr(el, "help", (v) => d.help = v);
3642
- readStr(el, "oldHelp", (v) => d.oldHelp = v);
3643
- readStr(el, "statusBar", (v) => d.statusBar = v);
3644
- readStr(el, "oldStatusBar", (v) => d.oldStatusBar = v);
3645
- readStr(el, "comment", (v) => d.comment = v);
3646
- readStr(el, "oldComment", (v) => d.oldComment = v);
3647
- const undo = parseBool(el, "ua");
3648
- if (undo) d.undo = undo;
3649
- const rejected = parseBool(el, "ra");
3650
- if (rejected) d.rejected = rejected;
3651
- const formula = findChild(el, "formula");
3652
- if (formula) d.formula = textOf(formula) ?? "";
3653
- const oldFormula = findChild(el, "oldFormula");
3654
- if (oldFormula) d.oldFormula = textOf(oldFormula) ?? "";
3655
- return {
3656
- type: "definedName",
3657
- data: d
3658
- };
3659
- }
3660
- case "rcmt": {
3661
- const d = {
3662
- sheetId: Number(attr(el, "sheetId") ?? "0"),
3663
- cell: attr(el, "cell") ?? "",
3664
- guid: attr(el, "guid") ?? "",
3665
- author: attr(el, "author") ?? ""
3666
- };
3667
- const action = attr(el, "action");
3668
- if (action) d.action = action;
3669
- readBool(el, "alwaysShow", (v) => d.alwaysShow = v);
3670
- readBool(el, "old", (v) => d.old = v);
3671
- readBool(el, "hiddenRow", (v) => d.hiddenRow = v);
3672
- readBool(el, "hiddenColumn", (v) => d.hiddenColumn = v);
3673
- readNum(el, "oldLength", (v) => d.oldLength = v);
3674
- readNum(el, "newLength", (v) => d.newLength = v);
3675
- return {
3676
- type: "comment",
3677
- data: d
3678
- };
3679
- }
3680
- case "rqt": return {
3681
- type: "queryTableField",
3682
- data: {
3683
- sheetId: Number(attr(el, "sheetId") ?? "0"),
3684
- ref: attr(el, "ref") ?? "",
3685
- fieldId: Number(attr(el, "fieldId") ?? "0")
3686
- }
3687
- };
3688
- case "rcft": {
3689
- const d = { rId: Number(attr(el, "rId") ?? "0") };
3690
- const undo = parseBool(el, "ua");
3691
- if (undo) d.undo = undo;
3692
- const rejected = parseBool(el, "ra");
3693
- if (rejected) d.rejected = rejected;
3694
- const sheetId = attr(el, "sheetId");
3695
- if (sheetId !== void 0) d.sheetId = Number(sheetId);
3696
- return {
3697
- type: "conflict",
3698
- data: d
3699
- };
3700
- }
3701
- default: return;
3702
- }
3703
- }
3704
- const revisionLogDesc = {
3705
- kind: "custom",
3706
- stringify(opts, _ctx) {
3707
- if (opts.revisions.length === 0) return void 0;
3708
- return `<revisions xmlns="${S_NS}">${opts.revisions.map(stringifyEntry).join("")}</revisions>`;
3709
- },
3710
- parse(el, _ctx) {
3711
- const revisions = [];
3712
- for (const child of el.elements ?? []) {
3713
- if (child.type !== "element") continue;
3714
- const entry = parseEntry(child);
3715
- if (entry) revisions.push(entry);
3716
- }
3717
- return { revisions };
3718
- }
3719
- };
3720
- function readBool(el, name, set) {
3721
- const raw = attr(el, name);
3722
- if (raw === "1" || raw === "true") set(true);
3723
- }
3724
- function readNum(el, name, set) {
3725
- const raw = attr(el, name);
3726
- if (raw !== void 0) set(Number(raw));
3727
- }
3728
- function readStr(el, name, set) {
3729
- const raw = attr(el, name);
3730
- if (raw !== void 0) set(raw);
3731
- }
3732
- //#endregion
3733
- //#region src/parts/content-types.ts
3734
- /**
3735
- * Content Types module for XLSX packages.
3736
- *
3737
- * @module
3738
- */
3739
- const XLSX_MAIN = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
3740
- const XLSX_WORKSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
3741
- const XLSX_CHARTSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";
3742
- const XLSX_STYLES = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml";
3743
- const XLSX_SHARED_STRINGS = "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml";
3744
- const XLSX_THEME = "application/vnd.openxmlformats-officedocument.theme+xml";
3745
- const XLSX_CHART = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml";
3746
- const CUSTOM_PROPS = "application/vnd.openxmlformats-officedocument.custom-properties+xml";
3747
- const STATIC_XML = [
3748
- {
3749
- type: "Default",
3750
- contentType: "application/vnd.openxmlformats-package.relationships+xml",
3751
- key: "rels"
3752
- },
3753
- {
3754
- type: "Default",
3755
- contentType: "application/xml",
3756
- key: "xml"
3757
- },
3758
- {
3759
- type: "Override",
3760
- contentType: XLSX_MAIN,
3761
- key: "/xl/workbook.xml"
3762
- },
3763
- {
3764
- type: "Override",
3765
- contentType: "application/vnd.openxmlformats-package.core-properties+xml",
3766
- key: "/docProps/core.xml"
3767
- },
3768
- {
3769
- type: "Override",
3770
- contentType: "application/vnd.openxmlformats-officedocument.extended-properties+xml",
3771
- key: "/docProps/app.xml"
3772
- }
3773
- ].map((e) => e.type === "Default" ? `<Default ContentType="${e.contentType}" Extension="${e.key}"/>` : `<Override ContentType="${e.contentType}" PartName="${e.key}"/>`).join("");
3774
- var ContentTypes = class {
3775
- dynamicEntries = [];
3776
- addWorksheet(index) {
3777
- this.dynamicEntries.push({
3778
- type: "Override",
3779
- contentType: XLSX_WORKSHEET,
3780
- key: `/xl/worksheets/sheet${index}.xml`
3781
- });
3782
- }
3783
- addChartsheet(index) {
3784
- this.dynamicEntries.push({
3785
- type: "Override",
3786
- contentType: XLSX_CHARTSHEET,
3787
- key: `/xl/chartsheets/sheet${index}.xml`
3788
- });
3789
- }
3790
- addStyles() {
3791
- this.dynamicEntries.push({
3792
- type: "Override",
3793
- contentType: XLSX_STYLES,
3794
- key: "/xl/styles.xml"
3795
- });
3796
- }
3797
- addSharedStrings() {
3798
- this.dynamicEntries.push({
3799
- type: "Override",
3800
- contentType: XLSX_SHARED_STRINGS,
3801
- key: "/xl/sharedStrings.xml"
3802
- });
3803
- }
3804
- addTheme(index = 1) {
3805
- this.dynamicEntries.push({
3806
- type: "Override",
3807
- contentType: XLSX_THEME,
3808
- key: `/xl/theme/theme${index}.xml`
3809
- });
3810
- }
3811
- addCustomProperties() {
3812
- this.dynamicEntries.push({
3813
- type: "Override",
3814
- contentType: CUSTOM_PROPS,
3815
- key: "/docProps/custom.xml"
3816
- });
3817
- }
3818
- addChart(index) {
3819
- this.dynamicEntries.push({
3820
- type: "Override",
3821
- contentType: XLSX_CHART,
3822
- key: `/xl/charts/chart${index}.xml`
3823
- });
3824
- }
3825
- addDrawing(index) {
3826
- this.dynamicEntries.push({
3827
- type: "Override",
3828
- contentType: "application/vnd.openxmlformats-officedocument.drawing+xml",
3829
- key: `/xl/drawings/drawing${index}.xml`
3830
- });
3831
- }
3832
- addComments(index) {
3833
- this.dynamicEntries.push({
3834
- type: "Override",
3835
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
3836
- key: `/xl/comments${index}.xml`
3837
- });
3838
- }
3839
- addVmlDrawing() {
3840
- if (this.dynamicEntries.some((e) => e.type === "Default" && e.key === "vml")) return;
3841
- this.dynamicEntries.push({
3842
- type: "Default",
3843
- contentType: "application/vnd.openxmlformats-officedocument.vmlDrawing",
3844
- key: "vml"
3845
- });
3846
- }
3847
- addImageType(extension) {
3848
- const contentType = extension === "png" ? "image/png" : "image/jpeg";
3849
- if (this.dynamicEntries.some((e) => e.type === "Default" && e.key === extension)) return;
3850
- this.dynamicEntries.push({
3851
- type: "Default",
3852
- contentType,
3853
- key: extension
3854
- });
3855
- }
3856
- addPivotTable(index) {
3857
- this.dynamicEntries.push({
3858
- type: "Override",
3859
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",
3860
- key: `/xl/pivotTables/pivotTable${index}.xml`
3861
- });
3862
- }
3863
- addPivotCacheDefinition(index) {
3864
- this.dynamicEntries.push({
3865
- type: "Override",
3866
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml",
3867
- key: `/xl/pivotCache/pivotCacheDefinition${index}.xml`
3868
- });
3869
- }
3870
- addPivotCacheRecords(index) {
3871
- this.dynamicEntries.push({
3872
- type: "Override",
3873
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml",
3874
- key: `/xl/pivotCache/pivotCacheRecords${index}.xml`
3875
- });
3876
- }
3877
- addTable(index) {
3878
- this.dynamicEntries.push({
3879
- type: "Override",
3880
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
3881
- key: `/xl/tables/table${index}.xml`
3882
- });
3883
- }
3884
- addExternalLink(index) {
3885
- this.dynamicEntries.push({
3886
- type: "Override",
3887
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml",
3888
- key: `/xl/externalLinks/externalLink${index}.xml`
3889
- });
3890
- }
3891
- addCalcChain() {
3892
- this.dynamicEntries.push({
3893
- type: "Override",
3894
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml",
3895
- key: "/xl/calcChain.xml"
3896
- });
3897
- }
3898
- addDialogsheet(index) {
3899
- this.dynamicEntries.push({
3900
- type: "Override",
3901
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
3902
- key: `/xl/dialogsheets/sheet${index}.xml`
3903
- });
3904
- }
3905
- addRevisionHeaders() {
3906
- this.dynamicEntries.push({
3907
- type: "Override",
3908
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml",
3909
- key: "/xl/revisionHeaders.xml"
3910
- });
3911
- }
3912
- addRevisionLog(index) {
3913
- this.dynamicEntries.push({
3914
- type: "Override",
3915
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml",
3916
- key: `/xl/revisions/revision${index}.xml`
3917
- });
3918
- }
3919
- addUsers() {
3920
- this.dynamicEntries.push({
3921
- type: "Override",
3922
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.users+xml",
3923
- key: "/xl/users.xml"
3924
- });
3925
- }
3926
- addQueryTable(index) {
3927
- this.dynamicEntries.push({
3928
- type: "Override",
3929
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml",
3930
- key: `/xl/queryTables/queryTable${index}.xml`
3931
- });
3932
- }
3933
- addMetadata() {
3934
- this.dynamicEntries.push({
3935
- type: "Override",
3936
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",
3937
- key: "/xl/metadata.xml"
3938
- });
3939
- }
3940
- serialize() {
3941
- const p = ["<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">", STATIC_XML];
3942
- for (const e of this.dynamicEntries) if (e.type === "Default") p.push(`<Default ContentType="${e.contentType}" Extension="${e.key}"/>`);
3943
- else p.push(`<Override ContentType="${e.contentType}" PartName="${e.key}"/>`);
3944
- p.push("</Types>");
3945
- return p.join("");
3946
- }
3947
- };
3948
- //#endregion
3949
- //#region src/context.ts
3950
- /**
3951
- * XLSX compile context — write and read contexts for the descriptor pipeline.
3952
- *
3953
- * @module
3954
- */
3955
- /**
3956
- * XLSX-specific write context.
3957
- *
3958
- * Holds mutable state that accumulates during the compile phase:
3959
- * shared strings, styles, media, charts, content types, and relationships.
3960
- */
3961
- var XlsxWriteContext = class {
3962
- sharedStrings = new SharedStrings();
3963
- styles = new Styles();
3964
- media = new Media();
3965
- charts = new ChartCollection();
3966
- contentTypes = new ContentTypes();
3967
- workbookRels = new Relationships();
3968
- pivotCacheRefs = [];
3969
- addRelationship(type, target, _mode) {
3970
- const id = this.workbookRels.relationshipCount + 1;
3971
- this.workbookRels.addRelationship(id, type, target);
3972
- return `rId${id}`;
3973
- }
3974
- addMedia(_data, _type) {
3975
- return "";
3976
- }
3977
- /**
3978
- * Register a differential format and return its dxfId.
3979
- */
3980
- registerDxf(opts) {
3981
- return this.styles.registerDxf(opts);
3982
- }
3983
- };
3984
- /**
3985
- * XLSX-specific read context.
3986
- *
3987
- * Wraps an {@link XlsxDocument} to implement the core {@link ReadContext}
3988
- * interface used by the descriptor parse pipeline.
3989
- */
3990
- var XlsxReadContext = class {
3991
- xlsx;
3992
- /** Parsed shared strings for resolving cell values. */
3993
- sharedStrings;
3994
- /** Parsed styles (fonts, fills, borders, cellXfs). Set by parseWorkbook(). */
3995
- parsedStyles;
3996
- constructor(xlsx, sharedStrings) {
3997
- this.xlsx = xlsx;
3998
- this.sharedStrings = sharedStrings ?? [];
3999
- }
4000
- resolveRelationship(rId) {
4001
- const wbRels = this.xlsx.doc.get("xl/_rels/workbook.xml.rels");
4002
- if (!wbRels?.elements) return void 0;
4003
- for (const child of wbRels.elements) {
4004
- if (child.name !== "Relationship") continue;
4005
- if (child.attributes?.["Id"] === rId) {
4006
- const target = child.attributes["Target"];
4007
- if (!target) return void 0;
4008
- return target.startsWith("/") ? target.slice(1) : `xl/${target}`;
4009
- }
4010
- }
4011
- }
4012
- /**
4013
- * Resolve a relationship rId from a worksheet-level rels file.
4014
- * Worksheet rels paths: `xl/worksheets/sheet1.xml` → `xl/worksheets/_rels/sheet1.xml.rels`
4015
- */
4016
- resolveWorksheetRel(wsPath, rId) {
4017
- const relsPath = wsPathToRelsPath(wsPath);
4018
- const rels = this.xlsx.doc.get(relsPath);
4019
- if (!rels?.elements) return void 0;
4020
- for (const child of rels.elements) {
4021
- if (child.name !== "Relationship") continue;
4022
- if (child.attributes?.["Id"] === rId) {
4023
- const target = child.attributes["Target"];
4024
- if (!target) return void 0;
4025
- return resolveWsTarget(wsPath, target);
4026
- }
4027
- }
4028
- }
4029
- /**
4030
- * Get all relationships from a worksheet rels file matching a type fragment.
4031
- * e.g. `getWorksheetRelsByType(path, "/comments")` returns all comment relationships.
4032
- */
4033
- getWorksheetRelsByType(wsPath, typeFragment) {
4034
- const relsPath = wsPathToRelsPath(wsPath);
4035
- const rels = this.xlsx.doc.get(relsPath);
4036
- if (!rels?.elements) return [];
4037
- const result = [];
4038
- for (const child of rels.elements) {
4039
- if (child.name !== "Relationship") continue;
4040
- const type = child.attributes?.["Type"];
4041
- if (!type || !type.includes(typeFragment)) continue;
4042
- const rId = child.attributes?.["Id"];
4043
- const target = child.attributes?.["Target"];
4044
- if (rId && target) result.push({
4045
- rId,
4046
- target: resolveWsTarget(wsPath, target)
4047
- });
4048
- }
4049
- return result;
4050
- }
4051
- getPart(path) {
4052
- return this.xlsx.doc.get(path);
4053
- }
4054
- getRaw(path) {
4055
- return this.xlsx.doc.getRaw(path);
4056
- }
4057
- /**
4058
- * Resolve a cell style index to a StyleOptions object by looking up
4059
- * the parsed cellXfs table and substituting font/fill/border/numFmt indices
4060
- * with their resolved values.
4061
- */
4062
- resolveStyle(styleIndex) {
4063
- const ps = this.parsedStyles;
4064
- if (!ps) return void 0;
4065
- const { cellXfs, fonts, fills, borders, customNumFmtById } = ps;
4066
- if (!cellXfs || styleIndex >= cellXfs.length) return void 0;
4067
- const xf = cellXfs[styleIndex];
4068
- if (!xf) return void 0;
4069
- const result = {};
4070
- const fontId = xf.fontId;
4071
- if (fontId !== void 0 && fonts && fontId < fonts.length) result.font = fonts[fontId];
4072
- const fillId = xf.fillId;
4073
- if (fillId !== void 0 && fills && fillId < fills.length) result.fill = fills[fillId];
4074
- const borderId = xf.borderId;
4075
- if (borderId !== void 0 && borders && borderId < borders.length) result.border = borders[borderId];
4076
- const numFmtId = xf.numFmtId;
4077
- if (numFmtId !== void 0 && customNumFmtById) {
4078
- const code = customNumFmtById.get(numFmtId);
4079
- if (code !== void 0) result.numFmt = code;
4080
- }
4081
- if (xf.alignment) result.alignment = xf.alignment;
4082
- if (xf.protection) result.protection = xf.protection;
4083
- if (xf.quotePrefix) result.quotePrefix = xf.quotePrefix;
4084
- if (xf.pivotButton) result.pivotButton = xf.pivotButton;
4085
- return result;
4086
- }
4087
- };
4088
- /** Derive rels path from worksheet path. */
4089
- function wsPathToRelsPath(wsPath) {
4090
- const idx = wsPath.lastIndexOf("/");
4091
- return `${wsPath.substring(0, idx)}/_rels/${wsPath.substring(idx + 1)}.rels`;
4092
- }
4093
- /** Resolve a relative target from a worksheet rels file to an absolute archive path. */
4094
- function resolveWsTarget(wsPath, target) {
4095
- if (target.startsWith("/")) return target.slice(1);
4096
- const wsDir = wsPath.substring(0, wsPath.lastIndexOf("/"));
4097
- const parts = target.split("/");
4098
- const dirParts = wsDir.split("/");
4099
- for (const part of parts) if (part === "..") dirParts.pop();
4100
- else dirParts.push(part);
4101
- return dirParts.join("/");
4102
- }
4103
- //#endregion
4104
- export { Styles as C, calcChainDesc as S, aggregate as _, usersDesc as a, drawingDesc as b, buildTablePartsXml as c, TotalsRowFunction as d, tableDesc as f, PivotFilterType as g, pivotTableDesc as h, revisionLogDesc as i, workbookDesc as l, pivotCacheRecordsDesc as m, XlsxWriteContext as n, Media as o, pivotCacheDefDesc as p, revisionHeadersDesc as r, buildExternalReferencesXml as s, XlsxReadContext as t, TableType as u, collectUniqueValues as v, stylesDesc as w, chartsheetDesc as x, externalLinkDesc as y };
4105
-
4106
- //# sourceMappingURL=context-eqnGd7of.mjs.map