@office-open/xlsx 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
- import { AppProperties, BaseXmlComponent, ChartCollection, ChartSpace, Formatter, IgnoreIfEmptyXmlComponent, OoxmlMimeType, Relationships, buildCorePropertiesXmlString, compileMapping, createPacker, parseArchive, parseCorePropsElement, strFromU8, toJson, toUint8Array, unzipSync, zipAndConvert } from "@office-open/core";
1
+ import { AppProperties, BaseXmlComponent, ChartCollection, ChartSpace, Formatter, IgnoreIfEmptyXmlComponent, OoxmlMimeType, Relationships, TargetModeType, buildCorePropertiesXmlString, compileMapping, createPacker, derivePasswordHash, parseArchive, parseCorePropsElement, strFromU8, toJson, toUint8Array, unzipSync, zipAndConvert } from "@office-open/core";
2
2
  import { attr, attrNum, attrs, escapeXml, findChild, js2xml, selfCloseElement, textOf } from "@office-open/xml";
3
+ import { DefaultTheme } from "@office-open/core/theme";
3
4
  //#region src/file/content-types.ts
4
5
  /**
5
6
  * Content Types module for XLSX packages.
@@ -8,6 +9,7 @@ import { attr, attrNum, attrs, escapeXml, findChild, js2xml, selfCloseElement, t
8
9
  */
9
10
  const XLSX_MAIN = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
10
11
  const XLSX_WORKSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
12
+ const XLSX_CHARTSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";
11
13
  const XLSX_STYLES = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml";
12
14
  const XLSX_SHARED_STRINGS = "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml";
13
15
  const XLSX_THEME = "application/vnd.openxmlformats-officedocument.theme+xml";
@@ -51,6 +53,13 @@ var ContentTypes = class extends BaseXmlComponent {
51
53
  key: `/xl/worksheets/sheet${index}.xml`
52
54
  });
53
55
  }
56
+ addChartsheet(index) {
57
+ this.dynamicEntries.push({
58
+ type: "Override",
59
+ contentType: XLSX_CHARTSHEET,
60
+ key: `/xl/chartsheets/sheet${index}.xml`
61
+ });
62
+ }
54
63
  addStyles() {
55
64
  this.dynamicEntries.push({
56
65
  type: "Override",
@@ -131,6 +140,62 @@ var ContentTypes = class extends BaseXmlComponent {
131
140
  key: `/xl/pivotCache/pivotCacheRecords${index}.xml`
132
141
  });
133
142
  }
143
+ addTable(index) {
144
+ this.dynamicEntries.push({
145
+ type: "Override",
146
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
147
+ key: `/xl/tables/table${index}.xml`
148
+ });
149
+ }
150
+ addExternalLink(index) {
151
+ this.dynamicEntries.push({
152
+ type: "Override",
153
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml",
154
+ key: `/xl/externalLinks/externalLink${index}.xml`
155
+ });
156
+ }
157
+ addCalcChain() {
158
+ this.dynamicEntries.push({
159
+ type: "Override",
160
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml",
161
+ key: "/xl/calcChain.xml"
162
+ });
163
+ }
164
+ addDialogsheet(index) {
165
+ this.dynamicEntries.push({
166
+ type: "Override",
167
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
168
+ key: `/xl/dialogsheets/sheet${index}.xml`
169
+ });
170
+ }
171
+ addRevisionHeaders() {
172
+ this.dynamicEntries.push({
173
+ type: "Override",
174
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml",
175
+ key: "/xl/revisionHeaders.xml"
176
+ });
177
+ }
178
+ addRevisionLog(index) {
179
+ this.dynamicEntries.push({
180
+ type: "Override",
181
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml",
182
+ key: `/xl/revisions/revision${index}.xml`
183
+ });
184
+ }
185
+ addQueryTable(index) {
186
+ this.dynamicEntries.push({
187
+ type: "Override",
188
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml",
189
+ key: `/xl/queryTables/queryTable${index}.xml`
190
+ });
191
+ }
192
+ addMetadata() {
193
+ this.dynamicEntries.push({
194
+ type: "Override",
195
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml",
196
+ key: "/xl/metadata.xml"
197
+ });
198
+ }
134
199
  toXml(_context) {
135
200
  const p = ["<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">", STATIC_XML];
136
201
  for (const e of this.dynamicEntries) if (e.type === "Default") p.push(`<Default ContentType="${e.contentType}" Extension="${e.key}"/>`);
@@ -177,34 +242,84 @@ var Media = class {
177
242
  *
178
243
  * @module
179
244
  */
245
+ /**
246
+ * Build rich text run properties XML (CT_RPrElt).
247
+ * Exported for reuse by Comments and other components.
248
+ */
249
+ function buildRPrXml(pr) {
250
+ if (!pr) return "";
251
+ const parts = [];
252
+ if (pr.font) parts.push(`<rFont val="${escapeXml(pr.font)}"/>`);
253
+ if (pr.charset !== void 0) parts.push(`<charset val="${pr.charset}"/>`);
254
+ if (pr.family !== void 0) parts.push(`<family val="${pr.family}"/>`);
255
+ if (pr.bold) parts.push("<b/>");
256
+ if (pr.italic) parts.push("<i/>");
257
+ if (pr.strike) parts.push("<strike/>");
258
+ if (pr.outline) parts.push("<outline/>");
259
+ if (pr.shadow) parts.push("<shadow/>");
260
+ if (pr.condense) parts.push("<condense/>");
261
+ if (pr.extend) parts.push("<extend/>");
262
+ if (pr.color) {
263
+ const rgb = pr.color.length === 6 ? `FF${pr.color}` : pr.color;
264
+ parts.push(`<color rgb="${escapeXml(rgb)}"/>`);
265
+ }
266
+ if (pr.size !== void 0) parts.push(`<sz val="${pr.size}"/>`);
267
+ if (pr.underline) if (pr.underline === "none") parts.push("<u/>");
268
+ else parts.push(`<u val="${pr.underline}"/>`);
269
+ if (pr.vertAlign) parts.push(`<vertAlign val="${pr.vertAlign}"/>`);
270
+ if (pr.scheme) parts.push(`<scheme val="${pr.scheme}"/>`);
271
+ return parts.length > 0 ? `<rPr>${parts.join("")}</rPr>` : "";
272
+ }
273
+ /** Build a CT_Rst XML string from RichTextOptions. */
274
+ function buildRstXml(rst) {
275
+ const parts = [];
276
+ if (rst.runs && rst.runs.length > 0) for (const run of rst.runs) {
277
+ const rPr = buildRPrXml(run.properties);
278
+ parts.push(`<r>${rPr}<t>${escapeXml(run.text)}</t></r>`);
279
+ }
280
+ else if (rst.text !== void 0) parts.push(`<t>${escapeXml(rst.text)}</t>`);
281
+ if (rst.phonetics) for (const ph of rst.phonetics) parts.push(`<rPh sb="${ph.sb}" eb="${ph.eb}"><t>${escapeXml(ph.text)}</t></rPh>`);
282
+ return parts.join("");
283
+ }
180
284
  var SharedStrings = class extends BaseXmlComponent {
181
- strings = [];
285
+ entries = [];
286
+ /** Dedup map for plain strings only. Rich text is not deduped. */
182
287
  indexMap = /* @__PURE__ */ new Map();
183
288
  constructor() {
184
289
  super("sst");
185
290
  }
186
291
  /**
187
- * Register a string and return its index.
292
+ * Register a plain string and return its index.
188
293
  * Returns existing index if the string is already registered.
189
294
  */
190
295
  register(s) {
191
296
  const existing = this.indexMap.get(s);
192
297
  if (existing !== void 0) return existing;
193
- const idx = this.strings.length;
194
- this.strings.push(s);
298
+ const idx = this.entries.length;
299
+ this.entries.push(s);
195
300
  this.indexMap.set(s, idx);
196
301
  return idx;
197
302
  }
303
+ /**
304
+ * Register a rich text entry and return its index.
305
+ * Rich text is not deduped (each call creates a new entry).
306
+ */
307
+ registerRich(rst) {
308
+ const idx = this.entries.length;
309
+ this.entries.push(rst);
310
+ return idx;
311
+ }
198
312
  get count() {
199
- return this.strings.length;
313
+ return this.entries.length;
200
314
  }
201
315
  /**
202
316
  * Zero-allocation fast path: directly concatenate XML string.
203
317
  * Bypasses the IXmlableObject intermediate tree entirely.
204
318
  */
205
319
  toXml(_context) {
206
- const p = ["<sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"", ` count="${this.strings.length}" uniqueCount="${this.indexMap.size}">`];
207
- for (const s of this.strings) p.push(`<si><t>${escapeXml(s)}</t></si>`);
320
+ const p = ["<sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"", ` count="${this.entries.length}" uniqueCount="${this.indexMap.size}">`];
321
+ for (const entry of this.entries) if (typeof entry === "string") p.push(`<si><t>${escapeXml(entry)}</t></si>`);
322
+ else p.push(`<si>${buildRstXml(entry)}</si>`);
208
323
  p.push("</sst>");
209
324
  return p.join("");
210
325
  }
@@ -220,14 +335,14 @@ var SharedStrings = class extends BaseXmlComponent {
220
335
  * @module
221
336
  */
222
337
  function fontKey(f) {
223
- 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.fontName ?? ""}`;
338
+ 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.fontName ?? ""}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}`;
224
339
  }
225
340
  function fillKey(f) {
226
- return `t${f.type ?? ""}c${f.color ?? ""}p${f.patternType ?? ""}`;
341
+ return `t${f.type ?? ""}c${f.color ?? ""}p${f.patternType ?? ""}bg${f.bgColor ?? ""}g${f.stops?.map((s) => `${s.position}_${s.color}`).join("|") ?? ""}`;
227
342
  }
228
343
  function borderKey(b) {
229
344
  const sk = (o) => `${o?.style ?? ""}_${o?.color ?? ""}`;
230
- return `t${sk(b.top)}b${sk(b.bottom)}l${sk(b.left)}r${sk(b.right)}d${sk(b.diagonal)}`;
345
+ 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)}`;
231
346
  }
232
347
  const BUILTIN_NUMFMTS = {
233
348
  General: 0,
@@ -277,6 +392,12 @@ var Styles = class extends BaseXmlComponent {
277
392
  }];
278
393
  cellXfKeys = /* @__PURE__ */ new Map();
279
394
  dxfs = [];
395
+ colors;
396
+ tableStyles;
397
+ /** Custom cell styles (CT_CellStyles) */
398
+ customCellStyles;
399
+ /** Style sheet extensions (CT_ExtensionList) */
400
+ styleExtensions;
280
401
  constructor() {
281
402
  super("styleSheet");
282
403
  this.fontKeys.set(fontKey(this.fonts[0]), 0);
@@ -295,7 +416,11 @@ var Styles = class extends BaseXmlComponent {
295
416
  fillId: this.registerFill(opts.fill),
296
417
  borderId: this.registerBorder(opts.border),
297
418
  numFmtId: this.registerNumFmt(opts.numFmt),
298
- alignment: opts.alignment
419
+ alignment: opts.alignment,
420
+ quotePrefix: opts.quotePrefix,
421
+ pivotButton: opts.pivotButton,
422
+ applyProtection: opts.applyProtection,
423
+ protection: opts.protection
299
424
  };
300
425
  const key = this.cellXfKey(xf);
301
426
  const existing = this.cellXfKeys.get(key);
@@ -314,6 +439,21 @@ var Styles = class extends BaseXmlComponent {
314
439
  this.dxfs.push(opts);
315
440
  return idx;
316
441
  }
442
+ /**
443
+ * Set color palette (indexed colors and MRU colors).
444
+ */
445
+ setColors(opts) {
446
+ this.colors = opts;
447
+ }
448
+ setTableStyles(styles) {
449
+ this.tableStyles = styles;
450
+ }
451
+ setExtensions(extensions) {
452
+ this.styleExtensions = extensions;
453
+ }
454
+ setCustomCellStyles(styles) {
455
+ this.customCellStyles = styles;
456
+ }
317
457
  registerFont(opts) {
318
458
  if (!opts) return 0;
319
459
  const key = fontKey(opts);
@@ -356,8 +496,10 @@ var Styles = class extends BaseXmlComponent {
356
496
  }
357
497
  cellXfKey(xf) {
358
498
  const a = xf.alignment;
359
- const ak = a ? `h${a.horizontal ?? ""}v${a.vertical ?? ""}w${a.wrapText ? 1 : 0}r${a.textRotation ?? ""}i${a.indent ?? ""}` : "";
360
- return `${xf.fontId}|${xf.fillId}|${xf.borderId}|${xf.numFmtId}|${ak}`;
499
+ 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 ?? ""}` : "";
500
+ const pr = xf.protection;
501
+ const pk = pr ? `l${pr.locked ?? ""}h${pr.hidden ?? ""}` : "";
502
+ return `${xf.fontId}|${xf.fillId}|${xf.borderId}|${xf.numFmtId}|${ak}|qp${xf.quotePrefix ? 1 : 0}|pb${xf.pivotButton ? 1 : 0}|${pk}`;
361
503
  }
362
504
  /**
363
505
  * Zero-allocation fast path: directly concatenate XML string.
@@ -374,14 +516,30 @@ var Styles = class extends BaseXmlComponent {
374
516
  for (const f of this.fonts) p.push(`<font>${this.fontXmlStr(f)}</font>`);
375
517
  p.push("</fonts>");
376
518
  p.push(`<fills count="${this.fills.length}">`);
377
- for (const f of this.fills) {
519
+ for (const f of this.fills) if (f.type === "gradient" && f.stops && f.stops.length > 0) {
520
+ const gfAttrs = {};
521
+ if (f.gradientType && f.gradientType !== "linear") gfAttrs.type = f.gradientType;
522
+ if (f.gradientDegree !== void 0) gfAttrs.degree = f.gradientDegree;
523
+ if (f.gradientLeft !== void 0) gfAttrs.left = f.gradientLeft;
524
+ if (f.gradientRight !== void 0) gfAttrs.right = f.gradientRight;
525
+ if (f.gradientTop !== void 0) gfAttrs.top = f.gradientTop;
526
+ if (f.gradientBottom !== void 0) gfAttrs.bottom = f.gradientBottom;
527
+ const stopParts = f.stops.map((s) => `<stop position="${s.position}"><color rgb="FF${s.color}"/></stop>`).join("");
528
+ p.push(`<fill><gradientFill${attrs(gfAttrs)}>${stopParts}</gradientFill></fill>`);
529
+ } else {
378
530
  const patternAttrs = attrs({ patternType: f.patternType ?? "solid" });
379
- const fgColor = f.color ? `<fgColor rgb="FF${f.color}"/>` : "";
380
- p.push(fgColor ? `<fill><patternFill${patternAttrs}>${fgColor}</patternFill></fill>` : `<fill><patternFill${patternAttrs}/></fill>`);
531
+ const colorContent = (f.color ? `<fgColor rgb="FF${f.color}"/>` : f.colorIndexed !== void 0 ? `<fgColor indexed="${f.colorIndexed}"/>` : "") + (f.bgColor ? `<bgColor rgb="FF${f.bgColor}"/>` : "");
532
+ p.push(colorContent ? `<fill><patternFill${patternAttrs}>${colorContent}</patternFill></fill>` : `<fill><patternFill${patternAttrs}/></fill>`);
381
533
  }
382
534
  p.push("</fills>");
383
535
  p.push(`<borders count="${this.borders.length}">`);
384
- for (const b of this.borders) p.push(`<border>${this.borderXmlStr(b)}</border>`);
536
+ for (const b of this.borders) {
537
+ const bAttrs = [];
538
+ if (b.diagonalUp) bAttrs.push("diagonalUp=\"1\"");
539
+ if (b.diagonalDown) bAttrs.push("diagonalDown=\"1\"");
540
+ const bAttr = bAttrs.length ? ` ${bAttrs.join(" ")}` : "";
541
+ p.push(`<border${bAttr}>${this.borderXmlStr(b)}</border>`);
542
+ }
385
543
  p.push("</borders>");
386
544
  p.push("<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>");
387
545
  p.push(`<cellXfs count="${this.cellXfs.length}">`);
@@ -397,11 +555,29 @@ var Styles = class extends BaseXmlComponent {
397
555
  if (xf.fontId > 0) xAttrs.applyFont = 1;
398
556
  if (xf.fillId > 0) xAttrs.applyFill = 1;
399
557
  if (xf.borderId > 0) xAttrs.applyBorder = 1;
400
- const alignStr = xf.alignment ? this.alignmentXmlStr(xf.alignment) : "";
401
- p.push(alignStr ? `<xf${attrs(xAttrs)}>${alignStr}</xf>` : `<xf${attrs(xAttrs)}/>`);
558
+ if (xf.numFmtId > 0) xAttrs.applyNumberFormat = 1;
559
+ if (xf.quotePrefix) xAttrs.quotePrefix = 1;
560
+ if (xf.pivotButton) xAttrs.pivotButton = 1;
561
+ if (xf.applyProtection) xAttrs.applyProtection = 1;
562
+ if (xf.protection) xAttrs.applyProtection = xAttrs.applyProtection ?? 1;
563
+ const inner = (xf.alignment ? this.alignmentXmlStr(xf.alignment) : "") + (xf.protection ? this.protectionXmlStr(xf.protection) : "");
564
+ p.push(inner ? `<xf${attrs(xAttrs)}>${inner}</xf>` : `<xf${attrs(xAttrs)}/>`);
402
565
  }
403
566
  p.push("</cellXfs>");
404
- p.push("<cellStyles count=\"1\"><cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/></cellStyles>");
567
+ if (this.customCellStyles && this.customCellStyles.length > 0) {
568
+ const csParts = [`<cellStyles ${[`count="${this.customCellStyles.length + 1}"`].join(" ")}>`];
569
+ csParts.push("<cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/>");
570
+ for (const cs of this.customCellStyles) {
571
+ const attrs = [`name="${escapeXml(cs.name)}"`, `xfId="${cs.xfId}"`];
572
+ if (cs.builtinId !== void 0) attrs.push(`builtinId="${cs.builtinId}"`);
573
+ if (cs.customBuiltin) attrs.push("customBuiltin=\"1\"");
574
+ if (cs.iLevel !== void 0) attrs.push(`iLevel="${cs.iLevel}"`);
575
+ if (cs.hidden) attrs.push("hidden=\"1\"");
576
+ csParts.push(`<cellStyle ${attrs.join(" ")}/>`);
577
+ }
578
+ csParts.push("</cellStyles>");
579
+ p.push(csParts.join(""));
580
+ } else p.push("<cellStyles count=\"1\"><cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/></cellStyles>");
405
581
  if (this.dxfs.length > 0) {
406
582
  p.push(`<dxfs count="${this.dxfs.length}">`);
407
583
  for (const dxf of this.dxfs) {
@@ -413,13 +589,54 @@ var Styles = class extends BaseXmlComponent {
413
589
  dParts.push(`<fill><patternFill${patAttrs}>${bgColor}</patternFill></fill>`);
414
590
  }
415
591
  if (dxf.numFmt) dParts.push(`<numFmt formatCode="${escapeXml(dxf.numFmt)}"/>`);
592
+ if (dxf.border) dParts.push(`<border>${this.borderXmlStr(dxf.border)}</border>`);
416
593
  if (dParts.length > 0) p.push(`<dxf>${dParts.join("")}</dxf>`);
417
594
  else p.push("<dxf/>");
418
595
  }
419
596
  p.push("</dxfs>");
420
597
  } else p.push("<dxfs count=\"0\"/>");
421
- p.push("<tableStyles count=\"0\" defaultTableStyle=\"TableStyleMedium2\" defaultPivotStyle=\"PivotStyleLight16\"/>");
422
- p.push("<extLst/>");
598
+ if (this.tableStyles && this.tableStyles.length > 0) {
599
+ const tsParts = [`<tableStyles count="${this.tableStyles.length}" defaultTableStyle="TableStyleMedium2" defaultPivotStyle="PivotStyleLight16">`];
600
+ for (const ts of this.tableStyles) {
601
+ const tsAttrs = [`name="${escapeXml(ts.name)}"`];
602
+ if (ts.pivot) tsAttrs.push("pivot=\"1\"");
603
+ if (ts.elements && ts.elements.length > 0) {
604
+ tsParts.push(`<tableStyle ${tsAttrs.join(" ")}>`);
605
+ for (const el of ts.elements) {
606
+ const elAttrs = [`type="${el.type}"`];
607
+ if (el.dxfId !== void 0) elAttrs.push(`dxfId="${el.dxfId}"`);
608
+ if (el.button) elAttrs.push("button=\"1\"");
609
+ tsParts.push(`<tableStyleElement ${elAttrs.join(" ")}/>`);
610
+ }
611
+ tsParts.push("</tableStyle>");
612
+ } else tsParts.push(`<tableStyle ${tsAttrs.join(" ")}/>`);
613
+ }
614
+ tsParts.push("</tableStyles>");
615
+ p.push(tsParts.join(""));
616
+ } else p.push("<tableStyles count=\"0\" defaultTableStyle=\"TableStyleMedium2\" defaultPivotStyle=\"PivotStyleLight16\"/>");
617
+ if (this.colors) {
618
+ const c = this.colors;
619
+ const colorParts = ["<colors>"];
620
+ if (c.indexedColors && c.indexedColors.length > 0) {
621
+ colorParts.push("<indexedColors>");
622
+ for (const ic of c.indexedColors) colorParts.push(`<rgbColor rgb="${ic.rgb}"/>`);
623
+ colorParts.push("</indexedColors>");
624
+ }
625
+ if (c.mruColors && c.mruColors.length > 0) {
626
+ colorParts.push("<mruColors>");
627
+ for (const mc of c.mruColors) colorParts.push(`<color rgb="FF${mc}"/>`);
628
+ colorParts.push("</mruColors>");
629
+ }
630
+ colorParts.push("</colors>");
631
+ p.push(colorParts.join(""));
632
+ }
633
+ if (this.styleExtensions && this.styleExtensions.length > 0) {
634
+ const extParts = ["<extLst>"];
635
+ for (const ext of this.styleExtensions) if (ext.content) extParts.push(`<ext uri="${ext.uri}">${ext.content}</ext>`);
636
+ else extParts.push(`<ext uri="${ext.uri}"/>`);
637
+ extParts.push("</extLst>");
638
+ p.push(extParts.join(""));
639
+ } else p.push("<extLst/>");
423
640
  p.push("</styleSheet>");
424
641
  return p.join("");
425
642
  }
@@ -429,26 +646,38 @@ var Styles = class extends BaseXmlComponent {
429
646
  if (f.italic) parts.push("<i/>");
430
647
  if (f.underline) parts.push("<u/>");
431
648
  if (f.strike) parts.push("<strike/>");
649
+ if (f.outline) parts.push("<outline/>");
650
+ if (f.shadow) parts.push("<shadow/>");
651
+ if (f.condense) parts.push("<condense/>");
652
+ if (f.extend) parts.push("<extend/>");
432
653
  if (f.size) parts.push(`<sz val="${f.size}"/>`);
433
654
  if (f.color) parts.push(`<color rgb="FF${f.color}"/>`);
434
655
  if (f.fontName) parts.push(`<name val="${escapeXml(f.fontName)}"/>`);
656
+ if (f.charset !== void 0) parts.push(`<charset val="${f.charset}"/>`);
657
+ if (f.family !== void 0) parts.push(`<family val="${f.family}"/>`);
658
+ if (f.vertAlign) parts.push(`<vertAlign val="${f.vertAlign}"/>`);
659
+ if (f.scheme) parts.push(`<scheme val="${f.scheme}"/>`);
435
660
  return parts.join("");
436
661
  }
437
662
  borderXmlStr(b) {
438
663
  const parts = [];
664
+ const renderSide = (name, opts, required = true) => {
665
+ if (opts && opts.style && opts.style !== "none") {
666
+ const colorStr = opts.color ? `<color rgb="FF${opts.color}"/>` : "";
667
+ parts.push(`<${name} style="${opts.style}">${colorStr}</${name}>`);
668
+ } else if (required) parts.push(`<${name}/>`);
669
+ };
439
670
  for (const side of [
440
671
  "left",
441
672
  "right",
442
673
  "top",
443
674
  "bottom",
444
- "diagonal"
445
- ]) {
446
- const opts = b[side];
447
- if (opts && opts.style && opts.style !== "none") {
448
- const colorStr = opts.color ? `<color rgb="FF${opts.color}"/>` : "";
449
- parts.push(`<${side} style="${opts.style}">${colorStr}</${side}>`);
450
- } else parts.push(`<${side}/>`);
451
- }
675
+ "diagonal",
676
+ "vertical",
677
+ "horizontal"
678
+ ]) renderSide(side, b[side]);
679
+ renderSide("start", b.start, false);
680
+ renderSide("end", b.end, false);
452
681
  return parts.join("");
453
682
  }
454
683
  alignmentXmlStr(a) {
@@ -458,29 +687,17 @@ var Styles = class extends BaseXmlComponent {
458
687
  if (a.wrapText) aAttrs.wrapText = 1;
459
688
  if (a.textRotation !== void 0) aAttrs.textRotation = a.textRotation;
460
689
  if (a.indent !== void 0) aAttrs.indent = a.indent;
690
+ if (a.relativeIndent !== void 0) aAttrs.relativeIndent = a.relativeIndent;
691
+ if (a.justifyLastLine) aAttrs.justifyLastLine = 1;
692
+ if (a.shrinkToFit) aAttrs.shrinkToFit = 1;
693
+ if (a.readingOrder !== void 0) aAttrs.readingOrder = a.readingOrder;
461
694
  return `<alignment${attrs(aAttrs)}/>`;
462
695
  }
463
- };
464
- //#endregion
465
- //#region src/file/theme.ts
466
- /**
467
- * Default theme for XLSX files — matches Microsoft Office's output structure.
468
- * Produces xl/theme/theme1.xml that Excel accepts without repair warnings.
469
- *
470
- * The theme XML is completely static — identical for every XLSX file.
471
- * Pre-serialized as a string constant to avoid building the IXmlableObject
472
- * tree and re-serializing on every compile.
473
- *
474
- * @module
475
- */
476
- const THEME_XML = "<a:theme xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" name=\"Office Theme\"><a:themeElements><a:clrScheme name=\"Office\"><a:dk1><a:sysClr val=\"windowText\" lastClr=\"000000\"/></a:dk1><a:lt1><a:sysClr val=\"window\" lastClr=\"FFFFFF\"/></a:lt1><a:dk2><a:srgbClr val=\"44546A\"/></a:dk2><a:lt2><a:srgbClr val=\"E7E6E6\"/></a:lt2><a:accent1><a:srgbClr val=\"5B9BD5\"/></a:accent1><a:accent2><a:srgbClr val=\"ED7D31\"/></a:accent2><a:accent3><a:srgbClr val=\"A5A5A5\"/></a:accent3><a:accent4><a:srgbClr val=\"FFC000\"/></a:accent4><a:accent5><a:srgbClr val=\"4472C4\"/></a:accent5><a:accent6><a:srgbClr val=\"70AD47\"/></a:accent6><a:hlink><a:srgbClr val=\"0563C1\"/></a:hlink><a:folHlink><a:srgbClr val=\"954F72\"/></a:folHlink></a:clrScheme><a:fontScheme name=\"Office\"><a:majorFont><a:latin typeface=\"Calibri Light\" panose=\"020F0302020204030204\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:majorFont><a:minorFont><a:latin typeface=\"Calibri\" panose=\"020F0502020204030204\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:minorFont></a:fontScheme><a:fmtScheme name=\"Office\"><a:fillStyleLst><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:gradFill rotWithShape=\"1\"><a:gsLst><a:gs pos=\"0\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"110000\"/><a:satMod val=\"105000\"/><a:tint val=\"67000\"/></a:schemeClr></a:gs><a:gs pos=\"50000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"105000\"/><a:satMod val=\"103000\"/><a:tint val=\"73000\"/></a:schemeClr></a:gs><a:gs pos=\"100000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"105000\"/><a:satMod val=\"109000\"/><a:tint val=\"81000\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"5400000\" scaled=\"0\"/></a:gradFill><a:gradFill rotWithShape=\"1\"><a:gsLst><a:gs pos=\"0\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"102000\"/><a:satMod val=\"103000\"/><a:tint val=\"94000\"/></a:schemeClr></a:gs><a:gs pos=\"50000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"100000\"/><a:satMod val=\"110000\"/><a:shade val=\"100000\"/></a:schemeClr></a:gs><a:gs pos=\"100000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"99000\"/><a:satMod val=\"120000\"/><a:shade val=\"78000\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"5400000\" scaled=\"0\"/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w=\"6350\" cap=\"flat\" cmpd=\"sng\" algn=\"ctr\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:prstDash val=\"solid\"/><a:miter lim=\"800000\"/></a:ln><a:ln w=\"12700\" cap=\"flat\" cmpd=\"sng\" algn=\"ctr\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:prstDash val=\"solid\"/><a:miter lim=\"800000\"/></a:ln><a:ln w=\"19050\" cap=\"flat\" cmpd=\"sng\" algn=\"ctr\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:prstDash val=\"solid\"/><a:miter lim=\"800000\"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad=\"57150\" dist=\"19050\" dir=\"5400000\" algn=\"ctr\" rotWithShape=\"0\"><a:srgbClr val=\"000000\"><a:alpha val=\"63000\"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"><a:tint val=\"95000\"/><a:satMod val=\"170000\"/></a:schemeClr></a:solidFill><a:gradFill rotWithShape=\"1\"><a:gsLst><a:gs pos=\"0\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"102000\"/><a:satMod val=\"150000\"/><a:tint val=\"93000\"/><a:shade val=\"98000\"/></a:schemeClr></a:gs><a:gs pos=\"50000\"><a:schemeClr val=\"phClr\"><a:lumMod val=\"103000\"/><a:satMod val=\"130000\"/><a:tint val=\"98000\"/><a:shade val=\"90000\"/></a:schemeClr></a:gs><a:gs pos=\"100000\"><a:schemeClr val=\"phClr\"><a:satMod val=\"120000\"/><a:shade val=\"63000\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"5400000\" scaled=\"0\"/></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/></a:theme>";
477
- var DefaultTheme = class extends BaseXmlComponent {
478
- constructor() {
479
- super("a:theme");
480
- }
481
- /** Return pre-cached static theme XML — zero allocation. */
482
- toXml(_context) {
483
- return THEME_XML;
696
+ protectionXmlStr(pr) {
697
+ const prAttrs = {};
698
+ if (pr.locked !== void 0) prAttrs.locked = pr.locked ? 1 : 0;
699
+ if (pr.hidden !== void 0) prAttrs.hidden = pr.hidden ? 1 : 0;
700
+ return `<protection${attrs(prAttrs)}/>`;
484
701
  }
485
702
  };
486
703
  //#endregion
@@ -493,32 +710,305 @@ var DefaultTheme = class extends BaseXmlComponent {
493
710
  var WorkbookXml = class extends BaseXmlComponent {
494
711
  sheets;
495
712
  pivotCaches;
496
- constructor(sheets, pivotCaches) {
713
+ protection;
714
+ customViews;
715
+ fileRecoveryPr;
716
+ functionGroupNames;
717
+ webPublishing;
718
+ fileSharing;
719
+ workbookPr;
720
+ calcPr;
721
+ bookView;
722
+ volTypes;
723
+ webPublishObjects;
724
+ conformance;
725
+ constructor(sheets, pivotCaches, protection, customViews, fileRecoveryPr, functionGroups, webPublishing, fileSharing, workbookPr, calcPr, bookView, volTypes, webPublishObjects, conformance) {
497
726
  super("workbook");
498
727
  this.sheets = sheets;
499
728
  this.pivotCaches = pivotCaches ?? [];
729
+ this.protection = protection;
730
+ this.customViews = customViews;
731
+ this.fileRecoveryPr = fileRecoveryPr;
732
+ this.functionGroupNames = functionGroups ?? [];
733
+ this.webPublishing = webPublishing;
734
+ this.fileSharing = fileSharing;
735
+ this.workbookPr = workbookPr;
736
+ this.calcPr = calcPr;
737
+ this.bookView = bookView;
738
+ this.volTypes = volTypes;
739
+ this.webPublishObjects = webPublishObjects;
740
+ this.conformance = conformance;
500
741
  }
501
742
  toXml(_context) {
502
- const p = [
503
- "<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\">",
504
- "<fileVersion appName=\"xl\" lastEdited=\"7\" lowestEdited=\"6\" rupBuild=\"29929\"/>",
505
- "<workbookPr/>",
506
- "<bookViews><workbookView xWindow=\"0\" yWindow=\"0\" windowWidth=\"28800\" windowHeight=\"12300\"/></bookViews>",
507
- "<sheets>"
508
- ];
743
+ 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"${this.conformance ? ` conformance="${this.conformance}"` : ""}>`, "<fileVersion appName=\"xl\" lastEdited=\"7\" lowestEdited=\"6\" rupBuild=\"29929\"/>"];
744
+ if (this.fileSharing) {
745
+ const fileSharing = this.fileSharing;
746
+ const fsAttrs = [];
747
+ if (fileSharing.readOnlyRecommended) fsAttrs.push("readOnlyRecommended=\"1\"");
748
+ if (fileSharing.userName) fsAttrs.push(`userName="${escapeXml(fileSharing.userName)}"`);
749
+ if (fileSharing.reservationPassword) {
750
+ fsAttrs.push(`reservationPassword="${escapeXml(fileSharing.reservationPassword)}"`);
751
+ if (fileSharing.hashValue === void 0) {
752
+ const derived = derivePasswordHash(fileSharing.reservationPassword);
753
+ fsAttrs.push(`algorithmName="${escapeXml(derived.algorithmName)}"`);
754
+ fsAttrs.push(`hashValue="${escapeXml(derived.hashValue)}"`);
755
+ fsAttrs.push(`saltValue="${escapeXml(derived.saltValue)}"`);
756
+ fsAttrs.push(`spinCount="${derived.spinCount}"`);
757
+ }
758
+ }
759
+ if (fileSharing.algorithmName) fsAttrs.push(`algorithmName="${escapeXml(fileSharing.algorithmName)}"`);
760
+ if (fileSharing.hashValue) fsAttrs.push(`hashValue="${escapeXml(fileSharing.hashValue)}"`);
761
+ if (fileSharing.saltValue) fsAttrs.push(`saltValue="${escapeXml(fileSharing.saltValue)}"`);
762
+ if (fileSharing.spinCount !== void 0) fsAttrs.push(`spinCount="${fileSharing.spinCount}"`);
763
+ if (fsAttrs.length > 0) parts.push(`<fileSharing ${fsAttrs.join(" ")}/>`);
764
+ }
765
+ if (this.workbookPr) {
766
+ const wbPr = this.workbookPr;
767
+ const wbPrAttrs = [];
768
+ if (wbPr.date1904) wbPrAttrs.push("date1904=\"1\"");
769
+ if (wbPr.defaultThemeVersion !== void 0) wbPrAttrs.push(`defaultThemeVersion="${wbPr.defaultThemeVersion}"`);
770
+ if (wbPr.showObjects) wbPrAttrs.push(`showObjects="${escapeXml(wbPr.showObjects)}"`);
771
+ if (wbPr.hidePivotFieldList) wbPrAttrs.push("hidePivotFieldList=\"1\"");
772
+ if (wbPr.allowRefreshQuery) wbPrAttrs.push("allowRefreshQuery=\"1\"");
773
+ if (wbPr.filterPrivacy) wbPrAttrs.push("filterPrivacy=\"1\"");
774
+ if (wbPr.backupFile) wbPrAttrs.push("backupFile=\"1\"");
775
+ if (wbPr.codeName) wbPrAttrs.push(`codeName="${escapeXml(wbPr.codeName)}"`);
776
+ if (wbPr.showBorderUnselectedTables) wbPrAttrs.push("showBorderUnselectedTables=\"1\"");
777
+ if (wbPr.promptedSolutions) wbPrAttrs.push("promptedSolutions=\"1\"");
778
+ if (wbPr.showInkAnnotation === false) wbPrAttrs.push("showInkAnnotation=\"0\"");
779
+ if (wbPr.saveExternalLinkValues === false) wbPrAttrs.push("saveExternalLinkValues=\"0\"");
780
+ if (wbPr.updateLinks) wbPrAttrs.push(`updateLinks="${escapeXml(wbPr.updateLinks)}"`);
781
+ if (wbPr.showPivotChartFilter) wbPrAttrs.push("showPivotChartFilter=\"1\"");
782
+ if (wbPr.publishItems) wbPrAttrs.push("publishItems=\"1\"");
783
+ if (wbPr.checkCompatibility) wbPrAttrs.push("checkCompatibility=\"1\"");
784
+ if (wbPr.autoCompressPictures === false) wbPrAttrs.push("autoCompressPictures=\"0\"");
785
+ if (wbPr.refreshAllConnections) wbPrAttrs.push("refreshAllConnections=\"1\"");
786
+ parts.push(`<workbookPr${wbPrAttrs.length > 0 ? ` ${wbPrAttrs.join(" ")}` : ""}/>`);
787
+ } else parts.push("<workbookPr/>");
788
+ if (this.protection) {
789
+ const prot = this.protection;
790
+ const protAttrs = [];
791
+ if (prot.lockStructure) protAttrs.push("lockStructure=\"1\"");
792
+ if (prot.lockWindows) protAttrs.push("lockWindows=\"1\"");
793
+ if (prot.lockRevision) protAttrs.push("lockRevision=\"1\"");
794
+ if (prot.workbookPassword) {
795
+ protAttrs.push(`workbookPassword="${this.hashPassword(prot.workbookPassword)}"`);
796
+ if (prot.workbookHashValue === void 0) {
797
+ const wbDerived = derivePasswordHash(prot.workbookPassword);
798
+ protAttrs.push(`workbookAlgorithmName="${escapeXml(wbDerived.algorithmName)}"`);
799
+ protAttrs.push(`workbookHashValue="${escapeXml(wbDerived.hashValue)}"`);
800
+ protAttrs.push(`workbookSaltValue="${escapeXml(wbDerived.saltValue)}"`);
801
+ protAttrs.push(`workbookSpinCount="${wbDerived.spinCount}"`);
802
+ }
803
+ }
804
+ if (prot.workbookAlgorithmName) protAttrs.push(`workbookAlgorithmName="${escapeXml(prot.workbookAlgorithmName)}"`);
805
+ if (prot.workbookHashValue) protAttrs.push(`workbookHashValue="${escapeXml(prot.workbookHashValue)}"`);
806
+ if (prot.workbookSaltValue) protAttrs.push(`workbookSaltValue="${escapeXml(prot.workbookSaltValue)}"`);
807
+ if (prot.workbookSpinCount !== void 0) protAttrs.push(`workbookSpinCount="${prot.workbookSpinCount}"`);
808
+ if (prot.revisionsPassword) {
809
+ protAttrs.push(`revisionsPassword="${this.hashPassword(prot.revisionsPassword)}"`);
810
+ if (prot.revisionsHashValue === void 0) {
811
+ const revDerived = derivePasswordHash(prot.revisionsPassword);
812
+ protAttrs.push(`revisionsAlgorithmName="${escapeXml(revDerived.algorithmName)}"`);
813
+ protAttrs.push(`revisionsHashValue="${escapeXml(revDerived.hashValue)}"`);
814
+ protAttrs.push(`revisionsSaltValue="${escapeXml(revDerived.saltValue)}"`);
815
+ protAttrs.push(`revisionsSpinCount="${revDerived.spinCount}"`);
816
+ }
817
+ }
818
+ if (prot.revisionsAlgorithmName) protAttrs.push(`revisionsAlgorithmName="${escapeXml(prot.revisionsAlgorithmName)}"`);
819
+ if (prot.revisionsHashValue) protAttrs.push(`revisionsHashValue="${escapeXml(prot.revisionsHashValue)}"`);
820
+ if (prot.revisionsSaltValue) protAttrs.push(`revisionsSaltValue="${escapeXml(prot.revisionsSaltValue)}"`);
821
+ if (prot.revisionsSpinCount !== void 0) protAttrs.push(`revisionsSpinCount="${prot.revisionsSpinCount}"`);
822
+ if (prot.workbookPasswordCharacterSet) protAttrs.push(`workbookPasswordCharacterSet="${escapeXml(prot.workbookPasswordCharacterSet)}"`);
823
+ if (prot.revisionsPasswordCharacterSet) protAttrs.push(`revisionsPasswordCharacterSet="${escapeXml(prot.revisionsPasswordCharacterSet)}"`);
824
+ if (protAttrs.length > 0) parts.push(`<workbookProtection ${protAttrs.join(" ")}/>`);
825
+ }
826
+ if (this.bookView) {
827
+ const bv = this.bookView;
828
+ const bvAttrs = [];
829
+ if (bv.xWindow !== void 0) bvAttrs.push(`xWindow="${bv.xWindow}"`);
830
+ else bvAttrs.push("xWindow=\"0\"");
831
+ if (bv.yWindow !== void 0) bvAttrs.push(`yWindow="${bv.yWindow}"`);
832
+ else bvAttrs.push("yWindow=\"0\"");
833
+ if (bv.windowWidth !== void 0) bvAttrs.push(`windowWidth="${bv.windowWidth}"`);
834
+ else bvAttrs.push("windowWidth=\"28800\"");
835
+ if (bv.windowHeight !== void 0) bvAttrs.push(`windowHeight="${bv.windowHeight}"`);
836
+ else bvAttrs.push("windowHeight=\"12300\"");
837
+ if (bv.activeTab !== void 0) bvAttrs.push(`activeTab="${bv.activeTab}"`);
838
+ if (bv.autoFilterDateGrouping === false) bvAttrs.push("autoFilterDateGrouping=\"0\"");
839
+ if (bv.firstSheet !== void 0) bvAttrs.push(`firstSheet="${bv.firstSheet}"`);
840
+ if (bv.showHorizontalScroll === false) bvAttrs.push("showHorizontalScroll=\"0\"");
841
+ if (bv.showSheetTabs === false) bvAttrs.push("showSheetTabs=\"0\"");
842
+ if (bv.showVerticalScroll === false) bvAttrs.push("showVerticalScroll=\"0\"");
843
+ if (bv.tabRatio !== void 0) bvAttrs.push(`tabRatio="${bv.tabRatio}"`);
844
+ parts.push(`<bookViews><workbookView ${bvAttrs.join(" ")}/></bookViews>`);
845
+ } else parts.push("<bookViews><workbookView xWindow=\"0\" yWindow=\"0\" windowWidth=\"28800\" windowHeight=\"12300\"/></bookViews>");
846
+ parts.push("<sheets>");
509
847
  for (const s of this.sheets) {
510
848
  const stateAttr = s.state && s.state !== "visible" ? ` state="${s.state}"` : "";
511
- p.push(`<sheet name="${escapeXml(s.name)}" sheetId="${s.sheetId}" r:id="${s.rId}"${stateAttr}/>`);
849
+ parts.push(`<sheet name="${escapeXml(s.name)}" sheetId="${s.sheetId}" r:id="${s.rId}"${stateAttr}/>`);
850
+ }
851
+ parts.push("</sheets>");
852
+ if (this.functionGroupNames.length > 0) {
853
+ const functionGroupParts = [`<functionGroups builtInGroupCount="16">`];
854
+ for (const name of this.functionGroupNames) functionGroupParts.push(`<functionGroup name="${escapeXml(name)}"/>`);
855
+ functionGroupParts.push("</functionGroups>");
856
+ parts.push(functionGroupParts.join(""));
857
+ }
858
+ parts.push("<!--EXTERNAL_REFS-->");
859
+ if (this.calcPr) {
860
+ const cp = this.calcPr;
861
+ const cpAttrs = [];
862
+ cpAttrs.push(`calcId="${cp.calcId ?? 162913}"`);
863
+ if (cp.calcMode) cpAttrs.push(`calcMode="${escapeXml(cp.calcMode)}"`);
864
+ if (cp.fullCalcOnLoad) cpAttrs.push("fullCalcOnLoad=\"1\"");
865
+ if (cp.calcOnSave === false) cpAttrs.push("calcOnSave=\"0\"");
866
+ if (cp.forceFullCalc) cpAttrs.push("forceFullCalc=\"1\"");
867
+ if (cp.concurrentCalc === false) cpAttrs.push("concurrentCalc=\"0\"");
868
+ if (cp.concurrentManualCount !== void 0) cpAttrs.push(`concurrentManualCount="${cp.concurrentManualCount}"`);
869
+ if (cp.iterate) cpAttrs.push("iterate=\"1\"");
870
+ if (cp.iterateCount !== void 0) cpAttrs.push(`iterateCount="${cp.iterateCount}"`);
871
+ if (cp.iterateDelta !== void 0) cpAttrs.push(`iterateDelta="${cp.iterateDelta}"`);
872
+ if (cp.refMode) cpAttrs.push(`refMode="${escapeXml(cp.refMode)}"`);
873
+ if (cp.fullPrecision === false) cpAttrs.push("fullPrecision=\"0\"");
874
+ if (cp.calcCompleted) cpAttrs.push("calcCompleted=\"1\"");
875
+ parts.push(`<calcPr ${cpAttrs.join(" ")}/>`);
876
+ } else parts.push("<calcPr calcId=\"162913\"/>");
877
+ if (this.customViews && this.customViews.length > 0) {
878
+ parts.push("<customWorkbookViews>");
879
+ for (const v of this.customViews) {
880
+ const vAttrs = [
881
+ `name="${escapeXml(v.name)}"`,
882
+ `guid="${escapeXml(v.guid)}"`,
883
+ `windowWidth="${v.windowWidth}"`,
884
+ `windowHeight="${v.windowHeight}"`,
885
+ `activeSheetId="${v.activeSheetId}"`
886
+ ];
887
+ if (v.xWindow !== void 0) vAttrs.push(`xWindow="${v.xWindow}"`);
888
+ if (v.yWindow !== void 0) vAttrs.push(`yWindow="${v.yWindow}"`);
889
+ if (v.showFormulaBar === false) vAttrs.push("showFormulaBar=\"0\"");
890
+ if (v.showStatusbar === false) vAttrs.push("showStatusbar=\"0\"");
891
+ if (v.showHorizontalScroll === false) vAttrs.push("showHorizontalScroll=\"0\"");
892
+ if (v.showVerticalScroll === false) vAttrs.push("showVerticalScroll=\"0\"");
893
+ if (v.showSheetTabs === false) vAttrs.push("showSheetTabs=\"0\"");
894
+ if (v.tabRatio !== void 0) vAttrs.push(`tabRatio="${v.tabRatio}"`);
895
+ if (v.includeHiddenRowCol === false) vAttrs.push("includeHiddenRowCol=\"0\"");
896
+ if (v.includePrintSettings === false) vAttrs.push("includePrintSettings=\"0\"");
897
+ if (v.personalView) vAttrs.push("personalView=\"1\"");
898
+ if (v.maximized) vAttrs.push("maximized=\"1\"");
899
+ if (v.minimized) vAttrs.push("minimized=\"1\"");
900
+ if (v.autoUpdate) vAttrs.push("autoUpdate=\"1\"");
901
+ if (v.mergeInterval !== void 0) vAttrs.push(`mergeInterval="${v.mergeInterval}"`);
902
+ if (v.changesSavedWin) vAttrs.push("changesSavedWin=\"1\"");
903
+ if (v.onlySync) vAttrs.push("onlySync=\"1\"");
904
+ if (v.showComments) vAttrs.push(`showComments="${escapeXml(v.showComments)}"`);
905
+ parts.push(`<customWorkbookView ${vAttrs.join(" ")}/>`);
906
+ }
907
+ parts.push("</customWorkbookViews>");
512
908
  }
513
- p.push("</sheets>");
514
- p.push("<calcPr calcId=\"162913\"/>");
515
909
  if (this.pivotCaches.length > 0) {
516
- p.push("<pivotCaches>");
517
- for (const pc of this.pivotCaches) p.push(`<pivotCache cacheId="${pc.cacheId}" r:id="${pc.rId}"/>`);
518
- p.push("</pivotCaches>");
910
+ parts.push("<pivotCaches>");
911
+ for (const pc of this.pivotCaches) parts.push(`<pivotCache cacheId="${pc.cacheId}" r:id="${pc.rId}"/>`);
912
+ parts.push("</pivotCaches>");
519
913
  }
520
- p.push("</workbook>");
521
- return p.join("");
914
+ if (this.webPublishing) {
915
+ const webPublishing = this.webPublishing;
916
+ const wpAttrs = [];
917
+ if (webPublishing.css === false) wpAttrs.push("css=\"0\"");
918
+ if (webPublishing.thicket === false) wpAttrs.push("thicket=\"0\"");
919
+ if (webPublishing.longFileNames === false) wpAttrs.push("longFileNames=\"0\"");
920
+ if (webPublishing.vml) wpAttrs.push("vml=\"1\"");
921
+ if (webPublishing.allowPng) wpAttrs.push("allowPng=\"1\"");
922
+ if (webPublishing.targetScreenSize && webPublishing.targetScreenSize !== "800x600") wpAttrs.push(`targetScreenSize="${webPublishing.targetScreenSize}"`);
923
+ if (webPublishing.dpi !== void 0 && webPublishing.dpi !== 96) wpAttrs.push(`dpi="${webPublishing.dpi}"`);
924
+ if (webPublishing.codePage !== void 0) wpAttrs.push(`codePage="${webPublishing.codePage}"`);
925
+ if (webPublishing.characterSet) wpAttrs.push(`characterSet="${escapeXml(webPublishing.characterSet)}"`);
926
+ parts.push(`<webPublishing ${wpAttrs.join(" ")}/>`);
927
+ }
928
+ if (this.fileRecoveryPr) {
929
+ const fileRecovery = this.fileRecoveryPr;
930
+ const frpAttrs = [];
931
+ if (fileRecovery.autoRecover === false) frpAttrs.push("autoRecover=\"0\"");
932
+ if (fileRecovery.crashSave) frpAttrs.push("crashSave=\"1\"");
933
+ if (fileRecovery.dataExtractLoad) frpAttrs.push("dataExtractLoad=\"1\"");
934
+ if (fileRecovery.repairLoad) frpAttrs.push("repairLoad=\"1\"");
935
+ if (frpAttrs.length > 0) parts.push(`<fileRecoveryPr ${frpAttrs.join(" ")}/>`);
936
+ }
937
+ if (this.webPublishObjects && this.webPublishObjects.length > 0) {
938
+ const wpoParts = [`<webPublishObjects count="${this.webPublishObjects.length}">`];
939
+ for (const wpo of this.webPublishObjects) {
940
+ const wpoAttrs = [`r:id="${escapeXml(wpo.rId)}"`];
941
+ if (wpo.destinationFile) wpoAttrs.push(`destinationFile="${escapeXml(wpo.destinationFile)}"`);
942
+ if (wpo.autoRepublish) wpoAttrs.push("autoRepublish=\"1\"");
943
+ if (wpo.title) wpoAttrs.push(`title="${escapeXml(wpo.title)}"`);
944
+ if (wpo.sourceObject) wpoAttrs.push(`sourceObject="${escapeXml(wpo.sourceObject)}"`);
945
+ wpoParts.push(`<webPublishObject ${wpoAttrs.join(" ")}/>`);
946
+ }
947
+ wpoParts.push("</webPublishObjects>");
948
+ parts.push(wpoParts.join(""));
949
+ }
950
+ if (this.volTypes && this.volTypes.length > 0) {
951
+ const vtParts = [`<volTypes count="${this.volTypes.length}">`];
952
+ for (const vt of this.volTypes) {
953
+ const vtType = vt.type ?? "realTimeData";
954
+ const mains = vt.mains ?? [];
955
+ if (mains.length > 0) {
956
+ const mainParts = [];
957
+ for (const m of mains) {
958
+ const tpParts = [];
959
+ for (const topic of m.topics ?? []) {
960
+ let tpInner = `<v>${escapeXml(topic.value)}</v>`;
961
+ for (const stp of topic.stringTopics ?? []) tpInner += `<stp>${escapeXml(stp)}</stp>`;
962
+ for (const tr of topic.refs ?? []) tpInner += `<tr r="${escapeXml(tr.reference)}" s="${tr.sheetIndex}"/>`;
963
+ const tpAttr = topic.valueType && topic.valueType !== "n" ? ` t="${escapeXml(topic.valueType)}"` : "";
964
+ tpParts.push(`<tp${tpAttr}>${tpInner}</tp>`);
965
+ }
966
+ mainParts.push(`<main first="${escapeXml(m.first)}">${tpParts.join("")}</main>`);
967
+ }
968
+ vtParts.push(`<volType type="${vtType}">${mainParts.join("")}</volType>`);
969
+ } else vtParts.push(`<volType type="${vtType}"/>`);
970
+ }
971
+ vtParts.push("</volTypes>");
972
+ parts.push(vtParts.join(""));
973
+ }
974
+ parts.push("</workbook>");
975
+ return parts.join("");
976
+ }
977
+ /**
978
+ * Generate tableParts XML fragment for embedding in a worksheet.
979
+ * This is called by the compiler to insert table references into the worksheet XML.
980
+ */
981
+ static buildTablePartsXml(tableParts) {
982
+ if (tableParts.length === 0) return "";
983
+ const parts = [`<tableParts count="${tableParts.length}">`];
984
+ for (const tp of tableParts) parts.push(`<tablePart r:id="${tp.rId}"/>`);
985
+ parts.push("</tableParts>");
986
+ return parts.join("");
987
+ }
988
+ /**
989
+ * Generate externalReferences XML fragment for embedding in the workbook.
990
+ * This is called by the compiler to insert external reference entries.
991
+ */
992
+ static buildExternalReferencesXml(refs) {
993
+ if (refs.length === 0) return "";
994
+ const parts = ["<externalReferences>"];
995
+ for (const ref of refs) parts.push(`<externalReference r:id="${ref.rId}"/>`);
996
+ parts.push("</externalReferences>");
997
+ return parts.join("");
998
+ }
999
+ /** Legacy Excel password hash (XOR-based) */
1000
+ hashPassword(password) {
1001
+ let hash = 0;
1002
+ for (let i = 0; i < password.length; i++) {
1003
+ const c = password.charCodeAt(i);
1004
+ hash = (hash >> 14 & 1) + (hash << 1 & 32767);
1005
+ hash ^= c;
1006
+ hash = hash & 16384 ? hash ^ 1 : hash;
1007
+ }
1008
+ hash = (hash >> 14 & 1) + (hash << 1 & 32767);
1009
+ hash = (hash >> 14 & 1) + (hash << 1 & 32767);
1010
+ hash ^= password.length;
1011
+ return hash.toString(16).toUpperCase().padStart(4, "0");
522
1012
  }
523
1013
  };
524
1014
  //#endregion
@@ -540,10 +1030,13 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
540
1030
  mergeCells;
541
1031
  freezePanes;
542
1032
  protection;
1033
+ protectedRanges;
1034
+ scenarioOpts;
543
1035
  autoFilter;
544
1036
  images;
545
1037
  chartOptions;
546
1038
  dataValidations;
1039
+ dataValidationsDisablePrompts;
547
1040
  conditionalFormats;
548
1041
  hyperlinks;
549
1042
  comments;
@@ -552,6 +1045,28 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
552
1045
  tabColor;
553
1046
  sheetView;
554
1047
  pivotTableOptions;
1048
+ tableOptions;
1049
+ ignoredErrors;
1050
+ phoneticPr;
1051
+ backgroundImage;
1052
+ printOptions;
1053
+ sheetFormatPr;
1054
+ sheetPr;
1055
+ rowBreaks;
1056
+ colBreaks;
1057
+ customSheetViews;
1058
+ cellWatches;
1059
+ dataConsolidate;
1060
+ oleSize;
1061
+ drawingHF;
1062
+ legacyDrawingHF;
1063
+ selection;
1064
+ sheetCalcPr;
1065
+ ext;
1066
+ controls;
1067
+ customProperties;
1068
+ oleObjects;
1069
+ webPublishItems;
555
1070
  constructor(options) {
556
1071
  super("worksheet");
557
1072
  this.rows = options.rows ?? [];
@@ -559,10 +1074,13 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
559
1074
  this.mergeCells = options.mergeCells ?? [];
560
1075
  this.freezePanes = options.freezePanes;
561
1076
  this.protection = options.protection;
1077
+ this.protectedRanges = options.protectedRanges ?? [];
1078
+ this.scenarioOpts = options.scenarios;
562
1079
  this.autoFilter = options.autoFilter;
563
1080
  this.images = options.images ?? [];
564
1081
  this.chartOptions = options.charts ?? [];
565
1082
  this.dataValidations = options.dataValidations ?? [];
1083
+ this.dataValidationsDisablePrompts = options.dataValidationsDisablePrompts;
566
1084
  this.conditionalFormats = options.conditionalFormats ?? [];
567
1085
  this.hyperlinks = options.hyperlinks ?? [];
568
1086
  this.comments = options.comments ?? [];
@@ -571,6 +1089,28 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
571
1089
  this.tabColor = options.tabColor;
572
1090
  this.sheetView = options.sheetView;
573
1091
  this.pivotTableOptions = options.pivotTables ?? [];
1092
+ this.tableOptions = options.tables ?? [];
1093
+ this.ignoredErrors = options.ignoredErrors ?? [];
1094
+ this.phoneticPr = options.phoneticPr;
1095
+ this.backgroundImage = options.backgroundImage;
1096
+ this.printOptions = options.printOptions;
1097
+ this.sheetFormatPr = options.sheetFormatPr;
1098
+ this.sheetPr = options.sheetPr;
1099
+ this.rowBreaks = options.rowBreaks ?? [];
1100
+ this.colBreaks = options.colBreaks ?? [];
1101
+ this.customSheetViews = options.customSheetViews ?? [];
1102
+ this.cellWatches = options.cellWatches ?? [];
1103
+ this.dataConsolidate = options.dataConsolidate;
1104
+ this.oleSize = options.oleSize;
1105
+ this.drawingHF = options.drawingHF;
1106
+ this.legacyDrawingHF = options.legacyDrawingHF;
1107
+ this.selection = options.selection;
1108
+ this.sheetCalcPr = options.sheetCalcPr;
1109
+ this.ext = options.ext;
1110
+ this.controls = options.controls ?? [];
1111
+ this.customProperties = options.customProperties ?? [];
1112
+ this.oleObjects = options.oleObjects ?? [];
1113
+ this.webPublishItems = options.webPublishItems ?? [];
574
1114
  }
575
1115
  get imageOptions() {
576
1116
  return this.images;
@@ -590,6 +1130,12 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
590
1130
  get pivotTables() {
591
1131
  return this.pivotTableOptions;
592
1132
  }
1133
+ get tables() {
1134
+ return this.tableOptions;
1135
+ }
1136
+ get background() {
1137
+ return this.backgroundImage;
1138
+ }
593
1139
  /**
594
1140
  * Zero-allocation fast path: directly concatenate XML string.
595
1141
  * Bypasses the IXmlableObject intermediate tree entirely.
@@ -601,18 +1147,45 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
601
1147
  const p = ["<worksheet 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=\"x14ac xr xr2 xr3\" xmlns:x14ac=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac\" xmlns:xr=\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\" xmlns:xr2=\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\" xmlns:xr3=\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision3\">"];
602
1148
  const hasTabColor = !!this.tabColor;
603
1149
  const hasOutline = this.columns.some((c) => c.outlineLevel !== void 0);
604
- if (hasTabColor || hasOutline) {
1150
+ const sp = this.sheetPr;
1151
+ const hasSheetPrAttrs = sp && (sp.syncHorizontal || sp.syncVertical || sp.syncRef || sp.transitionEvaluation || sp.transitionEntry || sp.published || sp.filterMode || sp.enableFormatConditionsCalculation);
1152
+ if (hasTabColor || hasOutline || hasSheetPrAttrs) {
605
1153
  const prParts = [];
1154
+ const prAttrs = {};
1155
+ if (sp?.syncHorizontal) prAttrs.syncHorizontal = 1;
1156
+ if (sp?.syncVertical) prAttrs.syncVertical = 1;
1157
+ if (sp?.syncRef) prAttrs.syncRef = sp.syncRef;
1158
+ if (sp?.transitionEvaluation) prAttrs.transitionEvaluation = 1;
1159
+ if (sp?.transitionEntry) prAttrs.transitionEntry = 1;
1160
+ if (sp?.published) prAttrs.published = 1;
1161
+ if (sp?.filterMode) prAttrs.filterMode = 1;
1162
+ if (sp?.enableFormatConditionsCalculation) prAttrs.enableFormatConditionsCalculation = 1;
606
1163
  if (this.tabColor) {
607
1164
  const tc = this.tabColor;
608
1165
  const tcAttrs = {};
609
1166
  if (tc.rgb) tcAttrs.rgb = tc.rgb;
610
1167
  if (tc.theme !== void 0) tcAttrs.theme = tc.theme;
611
1168
  if (tc.tint !== void 0) tcAttrs.tint = tc.tint;
1169
+ if (tc.indexed !== void 0) tcAttrs.indexed = tc.indexed;
612
1170
  prParts.push(`<tabColor${attrs(tcAttrs)}/>`);
613
1171
  }
614
- if (hasOutline) prParts.push("<outlinePr summaryBelow=\"1\" summaryRight=\"1\"/>");
615
- p.push(`<sheetPr>${prParts.join("")}</sheetPr>`);
1172
+ if (hasOutline) {
1173
+ const outAttrs = {
1174
+ summaryBelow: 1,
1175
+ summaryRight: 1
1176
+ };
1177
+ if (sp?.outlineApplyStyles) outAttrs.applyStyles = 1;
1178
+ if (sp?.outlineShowSymbols === false) outAttrs.showOutlineSymbols = 0;
1179
+ prParts.push(`<outlinePr${attrs(outAttrs)}/>`);
1180
+ }
1181
+ if (this.pageSetup?.fitToWidth || this.pageSetup?.fitToHeight || this.pageSetup?.autoPageBreaks) {
1182
+ const psupAttrs = {};
1183
+ if (this.pageSetup?.fitToWidth || this.pageSetup?.fitToHeight) psupAttrs.fitToPage = 1;
1184
+ if (this.pageSetup?.autoPageBreaks) psupAttrs.autoPageBreaks = 1;
1185
+ prParts.push(`<pageSetUpPr${attrs(psupAttrs)}/>`);
1186
+ }
1187
+ const prAttrStr = Object.keys(prAttrs).length > 0 ? attrs(prAttrs) : "";
1188
+ p.push(`<sheetPr${prAttrStr}>${prParts.join("")}</sheetPr>`);
616
1189
  }
617
1190
  const maxRow = this.rows.length;
618
1191
  let maxCol = 0;
@@ -621,6 +1194,7 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
621
1194
  const dimRef = `A1:${this.defaultCellRef(maxRow, maxCol)}`;
622
1195
  p.push(`<dimension ref="${dimRef}"/>`);
623
1196
  }
1197
+ const pivotSelXml = this.sheetView?.pivotSelections ? this.sheetView.pivotSelections.map((ps) => this.buildPivotSelectionXml(ps)).join("") : "";
624
1198
  if (this.freezePanes) {
625
1199
  const fp = this.freezePanes;
626
1200
  const ySplit = fp.row ? fp.row : 0;
@@ -630,12 +1204,26 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
630
1204
  const topLeftCell = this.defaultCellRef(topRow, leftCol);
631
1205
  const activePane = ySplit > 0 && xSplit > 0 ? "bottomRight" : ySplit > 0 ? "bottomLeft" : "topRight";
632
1206
  const svAttrs = this.buildSheetViewAttrs();
633
- p.push(`<sheetViews><sheetView${svAttrs}>`, `<pane ySplit="${ySplit}" xSplit="${xSplit}" topLeftCell="${topLeftCell}" activePane="${activePane}" state="frozen"/>`, "</sheetView></sheetViews>");
1207
+ p.push(`<sheetViews><sheetView${svAttrs}>`, `<pane ySplit="${ySplit}" xSplit="${xSplit}" topLeftCell="${topLeftCell}" activePane="${activePane}" state="frozen"/>`, this.selection ? this.buildSelectionXml(this.selection) : "", pivotSelXml, "</sheetView></sheetViews>");
634
1208
  } else {
635
1209
  const svAttrs = this.buildSheetViewAttrs();
636
- p.push(`<sheetViews><sheetView${svAttrs}/></sheetViews>`);
1210
+ const innerXml = (this.selection ? this.buildSelectionXml(this.selection) : "") + pivotSelXml;
1211
+ if (innerXml) p.push(`<sheetViews><sheetView${svAttrs}>${innerXml}</sheetView></sheetViews>`);
1212
+ else p.push(`<sheetViews><sheetView${svAttrs}/></sheetViews>`);
637
1213
  }
638
- p.push("<sheetFormatPr defaultRowHeight=\"15\"/>");
1214
+ if (this.sheetFormatPr) {
1215
+ const sfp = this.sheetFormatPr;
1216
+ const sfpAttrs = {};
1217
+ if (sfp.baseColWidth !== void 0) sfpAttrs.baseColWidth = sfp.baseColWidth;
1218
+ if (sfp.defaultColWidth !== void 0) sfpAttrs.defaultColWidth = sfp.defaultColWidth;
1219
+ sfpAttrs.defaultRowHeight = sfp.defaultRowHeight ?? 15;
1220
+ if (sfp.zeroHeight) sfpAttrs.zeroHeight = 1;
1221
+ if (sfp.thickTop) sfpAttrs.thickTop = 1;
1222
+ if (sfp.thickBottom) sfpAttrs.thickBottom = 1;
1223
+ if (sfp.outlineLevelRow !== void 0) sfpAttrs.outlineLevelRow = sfp.outlineLevelRow;
1224
+ if (sfp.outlineLevelCol !== void 0) sfpAttrs.outlineLevelCol = sfp.outlineLevelCol;
1225
+ p.push(`<sheetFormatPr${attrs(sfpAttrs)}/>`);
1226
+ } else p.push("<sheetFormatPr defaultRowHeight=\"15\"/>");
639
1227
  if (this.columns.length > 0) {
640
1228
  p.push("<cols>");
641
1229
  for (const col of this.columns) {
@@ -650,6 +1238,8 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
650
1238
  if (col.hidden) colAttrs.hidden = 1;
651
1239
  if (col.outlineLevel !== void 0) colAttrs.outlineLevel = col.outlineLevel;
652
1240
  if (col.collapsed) colAttrs.collapsed = 1;
1241
+ if (col.bestFit) colAttrs.bestFit = 1;
1242
+ if (col.phonetic) colAttrs.phonetic = 1;
653
1243
  p.push(selfCloseElement("col", attrs(colAttrs)));
654
1244
  }
655
1245
  p.push("</cols>");
@@ -664,6 +1254,11 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
664
1254
  rowAttrs.customHeight = 1;
665
1255
  }
666
1256
  if (rowOpts.hidden) rowAttrs.hidden = 1;
1257
+ if (rowOpts.spans) rowAttrs.spans = rowOpts.spans;
1258
+ if (rowOpts.customFormat) rowAttrs.customFormat = 1;
1259
+ if (rowOpts.thickTop) rowAttrs.thickTop = 1;
1260
+ if (rowOpts.thickBot) rowAttrs.thickBot = 1;
1261
+ if (rowOpts.ph) rowAttrs.ph = 1;
667
1262
  if (rowOpts.cells) {
668
1263
  const rowParts = [];
669
1264
  for (let j = 0; j < rowOpts.cells.length; j++) {
@@ -676,10 +1271,92 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
676
1271
  } else p.push(`<row${attrs(rowAttrs)}/>`);
677
1272
  }
678
1273
  p.push("</sheetData>");
1274
+ if (this.sheetCalcPr) {
1275
+ const scAttrs = [];
1276
+ if (this.sheetCalcPr.fullCalcOnLoad) scAttrs.push("fullCalcOnLoad=\"1\"");
1277
+ p.push(`<sheetCalcPr${scAttrs.length ? " " + scAttrs.join(" ") : ""}/>`);
1278
+ }
1279
+ if (this.rowBreaks.length > 0) {
1280
+ const brkParts = this.rowBreaks.map((b) => {
1281
+ const bAttrs = { id: b.id };
1282
+ if (b.min !== void 0) bAttrs.min = b.min;
1283
+ if (b.max !== void 0) bAttrs.max = b.max;
1284
+ if (b.manual) bAttrs.man = 1;
1285
+ if (b.pivot) bAttrs.pt = 1;
1286
+ return `<brk${attrs(bAttrs)}/>`;
1287
+ });
1288
+ p.push(`<rowBreaks count="${this.rowBreaks.length}" manualBreakCount="${this.rowBreaks.filter((b) => b.manual).length}">${brkParts.join("")}</rowBreaks>`);
1289
+ }
1290
+ if (this.colBreaks.length > 0) {
1291
+ const brkParts = this.colBreaks.map((b) => {
1292
+ const bAttrs = { id: b.id };
1293
+ if (b.min !== void 0) bAttrs.min = b.min;
1294
+ if (b.max !== void 0) bAttrs.max = b.max;
1295
+ if (b.manual) bAttrs.man = 1;
1296
+ if (b.pivot) bAttrs.pt = 1;
1297
+ return `<brk${attrs(bAttrs)}/>`;
1298
+ });
1299
+ p.push(`<colBreaks count="${this.colBreaks.length}" manualBreakCount="${this.colBreaks.filter((b) => b.manual).length}">${brkParts.join("")}</colBreaks>`);
1300
+ }
1301
+ if (this.customProperties.length > 0) {
1302
+ const cpParts = ["<customProperties>"];
1303
+ for (const cp of this.customProperties) cpParts.push(`<customPr name="${escapeXml(cp.name)}" r:id="${escapeXml(cp.rId)}"/>`);
1304
+ cpParts.push("</customProperties>");
1305
+ p.push(cpParts.join(""));
1306
+ }
1307
+ if (this.oleSize) p.push(`<oleSize ref="${escapeXml(this.oleSize)}"/>`);
1308
+ if (this.customSheetViews.length > 0) {
1309
+ p.push("<customSheetViews>");
1310
+ for (const csv of this.customSheetViews) {
1311
+ const csvAttrs = { guid: csv.guid };
1312
+ if (csv.scale !== void 0) csvAttrs.scale = csv.scale;
1313
+ if (csv.showPageBreaks) csvAttrs.showPageBreaks = 1;
1314
+ if (csv.showFormulas) csvAttrs.showFormulas = 1;
1315
+ if (csv.showGridLines === false) csvAttrs.showGridLines = 0;
1316
+ if (csv.showRowColHeaders === false) csvAttrs.showRowCol = 0;
1317
+ if (csv.outlineSymbols === false) csvAttrs.outlineSymbols = 0;
1318
+ if (csv.zeroValues === false) csvAttrs.zeroValues = 0;
1319
+ if (csv.fitToPage) csvAttrs.fitToPage = 1;
1320
+ if (csv.printArea) csvAttrs.printArea = 1;
1321
+ if (csv.filter) csvAttrs.filter = 1;
1322
+ if (csv.showAutoFilter) csvAttrs.showAutoFilter = 1;
1323
+ if (csv.hiddenRows) csvAttrs.hiddenRows = 1;
1324
+ if (csv.hiddenColumns) csvAttrs.hiddenColumns = 1;
1325
+ if (csv.state && csv.state !== "visible") csvAttrs.state = csv.state;
1326
+ if (csv.filterUnique) csvAttrs.filterUnique = 1;
1327
+ if (csv.view && csv.view !== "normal") csvAttrs.view = csv.view;
1328
+ p.push(`<customSheetView${attrs(csvAttrs)}/>`);
1329
+ }
1330
+ p.push("</customSheetViews>");
1331
+ }
1332
+ if (this.cellWatches.length > 0) {
1333
+ p.push("<cellWatches>");
1334
+ for (const cw of this.cellWatches) p.push(`<cellWatch r="${escapeXml(cw.r)}"/>`);
1335
+ p.push("</cellWatches>");
1336
+ }
1337
+ if (this.dataConsolidate) {
1338
+ const dc = this.dataConsolidate;
1339
+ const dcAttrs = {};
1340
+ if (dc.function && dc.function !== "sum") dcAttrs.function = dc.function;
1341
+ if (dc.topLabels) dcAttrs.topLabels = 1;
1342
+ if (dc.leftLabels) dcAttrs.leftLabels = 1;
1343
+ if (dc.startLabels) dcAttrs.startLabels = 1;
1344
+ if (dc.link) dcAttrs.link = 1;
1345
+ const refsInner = dc.refs?.map((r) => `<dataRef ref="${escapeXml(r)}"/>`).join("") ?? "";
1346
+ const refsXml = refsInner ? `<dataRefs>${refsInner}</dataRefs>` : "";
1347
+ if (refsXml || Object.keys(dcAttrs).length > 0) p.push(`<dataConsolidate${attrs(dcAttrs)}>${refsXml}</dataConsolidate>`);
1348
+ }
679
1349
  if (this.protection) {
680
1350
  const prot = this.protection;
681
1351
  const protAttrs = {};
682
1352
  if (prot.password) protAttrs.password = this.hashPassword(prot.password);
1353
+ let derived;
1354
+ if (prot.password !== void 0 && prot.hashValue === void 0) derived = derivePasswordHash(prot.password);
1355
+ protAttrs.algorithmName = prot.algorithmName ?? derived?.algorithmName;
1356
+ protAttrs.hashValue = prot.hashValue ?? derived?.hashValue;
1357
+ protAttrs.saltValue = prot.saltValue ?? derived?.saltValue;
1358
+ if (prot.spinCount !== void 0) protAttrs.spinCount = prot.spinCount;
1359
+ else if (derived) protAttrs.spinCount = derived.spinCount;
683
1360
  if (prot.sheet) protAttrs.sheet = 1;
684
1361
  if (prot.objects) protAttrs.objects = 1;
685
1362
  if (prot.scenarios) protAttrs.scenarios = 1;
@@ -698,17 +1375,74 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
698
1375
  if (prot.selectUnlockedCells) protAttrs.selectUnlockedCells = 1;
699
1376
  p.push(selfCloseElement("sheetProtection", attrs(protAttrs)));
700
1377
  }
1378
+ if (this.protectedRanges.length > 0) {
1379
+ const prParts = ["<protectedRanges>"];
1380
+ for (const pr of this.protectedRanges) {
1381
+ const prAttrs = {
1382
+ name: pr.name,
1383
+ sqref: pr.sqref
1384
+ };
1385
+ if (pr.password) prAttrs.password = this.hashPassword(pr.password);
1386
+ let prDerived;
1387
+ if (pr.password !== void 0 && pr.hashValue === void 0) prDerived = derivePasswordHash(pr.password);
1388
+ prAttrs.algorithmName = pr.algorithmName ?? prDerived?.algorithmName;
1389
+ prAttrs.hashValue = pr.hashValue ?? prDerived?.hashValue;
1390
+ prAttrs.saltValue = pr.saltValue ?? prDerived?.saltValue;
1391
+ if (pr.spinCount !== void 0) prAttrs.spinCount = pr.spinCount;
1392
+ else if (prDerived) prAttrs.spinCount = prDerived.spinCount;
1393
+ if (!!pr.securityDescriptor) prParts.push(`<protectedRange${attrs(prAttrs)}><securityDescriptor>${escapeXml(pr.securityDescriptor)}</securityDescriptor></protectedRange>`);
1394
+ else prParts.push(selfCloseElement("protectedRange", attrs(prAttrs)));
1395
+ }
1396
+ prParts.push("</protectedRanges>");
1397
+ p.push(prParts.join(""));
1398
+ }
1399
+ if (this.scenarioOpts) {
1400
+ const scParts = ["<scenarios"];
1401
+ const scAttrs = {};
1402
+ if (this.scenarioOpts.current !== void 0) scAttrs.current = this.scenarioOpts.current;
1403
+ if (this.scenarioOpts.show !== void 0) scAttrs.show = this.scenarioOpts.show;
1404
+ scParts[0] = `<scenarios${attrs(scAttrs)}>`;
1405
+ for (const scenario of this.scenarioOpts.scenarios) {
1406
+ const sAttrs = { name: scenario.name };
1407
+ if (scenario.count !== void 0) sAttrs.count = scenario.count;
1408
+ if (scenario.user) sAttrs.user = scenario.user;
1409
+ if (scenario.comment) sAttrs.comment = scenario.comment;
1410
+ if (scenario.hidden) sAttrs.hidden = true;
1411
+ if (scenario.locked) sAttrs.locked = true;
1412
+ const sParts = [`<scenario${attrs(sAttrs)}>`];
1413
+ for (const cell of scenario.inputCells) {
1414
+ const icAttrs = {
1415
+ r: cell.r,
1416
+ val: String(cell.val)
1417
+ };
1418
+ if (cell.deleted) icAttrs.deleted = true;
1419
+ if (cell.undone) icAttrs.undone = true;
1420
+ sParts.push(`<inputCells${attrs(icAttrs)}/>`);
1421
+ }
1422
+ sParts.push("</scenario>");
1423
+ scParts.push(sParts.join(""));
1424
+ }
1425
+ scParts.push("</scenarios>");
1426
+ p.push(scParts.join(""));
1427
+ }
701
1428
  if (this.autoFilter) if (typeof this.autoFilter === "string") p.push(selfCloseElement("autoFilter", attrs({ ref: this.autoFilter })));
702
1429
  else {
703
1430
  const af = this.autoFilter;
704
1431
  const inner = [];
705
1432
  for (const t10 of af.top10 ?? []) {
1433
+ const fcAttrs = { colId: t10.colId };
1434
+ if (t10.hiddenButton) fcAttrs.hiddenButton = 1;
1435
+ if (t10.showButton === false) fcAttrs.showButton = 0;
706
1436
  const t10Attrs = { val: t10.val };
707
1437
  if (t10.top === false) t10Attrs.top = 0;
708
1438
  if (t10.percent) t10Attrs.percent = 1;
709
- inner.push(`<filterColumn colId="${t10.colId}"><top10${attrs(t10Attrs)}/></filterColumn>`);
1439
+ if (t10.filterVal !== void 0) t10Attrs.filterVal = t10.filterVal;
1440
+ inner.push(`<filterColumn${attrs(fcAttrs)}><top10${attrs(t10Attrs)}/></filterColumn>`);
710
1441
  }
711
1442
  for (const cf of af.customFilters ?? []) {
1443
+ const fcAttrs = { colId: cf.colId };
1444
+ if (cf.hiddenButton) fcAttrs.hiddenButton = 1;
1445
+ if (cf.showButton === false) fcAttrs.showButton = 0;
712
1446
  const cfAttrs = {};
713
1447
  if (cf.and) cfAttrs.and = 1;
714
1448
  const filters = [];
@@ -718,16 +1452,60 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
718
1452
  filters.push(selfCloseElement("customFilter", attrs(fAttrs)));
719
1453
  }
720
1454
  if (cf.val2 !== void 0) filters.push(selfCloseElement("customFilter", attrs({ val: cf.val2 })));
721
- if (filters.length > 0) inner.push(`<filterColumn colId="${cf.colId}"><customFilters${attrs(cfAttrs)}>${filters.join("")}</customFilters></filterColumn>`);
1455
+ if (filters.length > 0) inner.push(`<filterColumn${attrs(fcAttrs)}><customFilters${attrs(cfAttrs)}>${filters.join("")}</customFilters></filterColumn>`);
1456
+ }
1457
+ for (const fi of af.filters ?? []) {
1458
+ const fcAttrs = { colId: fi.colId };
1459
+ const filtersAttrs = {};
1460
+ if (fi.blank) filtersAttrs.blank = 1;
1461
+ if (fi.calendarType) filtersAttrs.calendarType = fi.calendarType;
1462
+ const valParts = (fi.values ?? []).map((v) => `<filter val="${escapeXml(v)}"/>`);
1463
+ inner.push(`<filterColumn${attrs(fcAttrs)}><filters${attrs(filtersAttrs)}>${valParts.join("")}</filters></filterColumn>`);
722
1464
  }
723
1465
  if (af.sort && af.sort.length > 0) {
724
1466
  const sortParts = [];
725
1467
  for (const sc of af.sort) {
726
1468
  const scAttrs = { ref: sc.ref };
727
1469
  if (sc.descending) scAttrs.descending = 1;
1470
+ if (sc.sortBy) scAttrs.sortBy = sc.sortBy;
1471
+ if (sc.customList) scAttrs.customList = sc.customList;
1472
+ if (sc.iconId !== void 0) scAttrs.iconId = sc.iconId;
728
1473
  sortParts.push(selfCloseElement("sortCondition", attrs(scAttrs)));
729
1474
  }
730
- inner.push(`<sortState ref="${af.ref}">${sortParts.join("")}</sortState>`);
1475
+ const ssAttrs = { ref: af.ref };
1476
+ if (af.sortState?.columnSort) ssAttrs.columnSort = 1;
1477
+ if (af.sortState?.caseSensitive) ssAttrs.caseSensitive = 1;
1478
+ if (af.sortState?.sortMethod) ssAttrs.sortMethod = af.sortState.sortMethod;
1479
+ inner.push(`<sortState${attrs(ssAttrs)}>${sortParts.join("")}</sortState>`);
1480
+ }
1481
+ for (const cf of af.colorFilters ?? []) {
1482
+ const cfAttrs = {};
1483
+ if (cf.dxfId !== void 0) cfAttrs.dxfId = cf.dxfId;
1484
+ if (cf.cellColor === false) cfAttrs.cellColor = 0;
1485
+ inner.push(`<filterColumn colId="${cf.colId}"><colorFilter${attrs(cfAttrs)}/></filterColumn>`);
1486
+ }
1487
+ for (const if_ of af.iconFilters ?? []) {
1488
+ const ifAttrs = { iconSet: if_.iconSet };
1489
+ if (if_.iconId !== void 0) ifAttrs.iconId = if_.iconId;
1490
+ inner.push(`<filterColumn colId="${if_.colId}"><iconFilter${attrs(ifAttrs)}/></filterColumn>`);
1491
+ }
1492
+ for (const df of af.dynamicFilters ?? []) {
1493
+ const dfAttrs = { type: df.type };
1494
+ if (df.val !== void 0) dfAttrs.val = df.val;
1495
+ if (df.maxVal !== void 0) dfAttrs.maxVal = df.maxVal;
1496
+ if (df.valIso !== void 0) dfAttrs.valIso = df.valIso;
1497
+ if (df.maxValIso !== void 0) dfAttrs.maxValIso = df.maxValIso;
1498
+ inner.push(`<filterColumn colId="${df.colId}"><dynamicFilter${attrs(dfAttrs)}/></filterColumn>`);
1499
+ }
1500
+ for (const dg of af.dateGroupItems ?? []) {
1501
+ const dgAttrs = { dateTimeGrouping: dg.dateTimeGrouping };
1502
+ if (dg.year !== void 0) dgAttrs.year = dg.year;
1503
+ if (dg.month !== void 0) dgAttrs.month = dg.month;
1504
+ if (dg.day !== void 0) dgAttrs.day = dg.day;
1505
+ if (dg.hour !== void 0) dgAttrs.hour = dg.hour;
1506
+ if (dg.minute !== void 0) dgAttrs.minute = dg.minute;
1507
+ if (dg.second !== void 0) dgAttrs.second = dg.second;
1508
+ inner.push(`<filterColumn colId="${dg.colId}"><dateGroupItem${attrs(dgAttrs)}/></filterColumn>`);
731
1509
  }
732
1510
  if (inner.length > 0) p.push(`<autoFilter ref="${af.ref}">`, ...inner, "</autoFilter>");
733
1511
  else p.push(selfCloseElement("autoFilter", attrs({ ref: af.ref })));
@@ -741,6 +1519,13 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
741
1519
  }
742
1520
  p.push("</mergeCells>");
743
1521
  }
1522
+ if (this.phoneticPr) {
1523
+ const pp = this.phoneticPr;
1524
+ const ppAttrs = { fontId: pp.fontId };
1525
+ if (pp.type && pp.type !== "fullwidthKatakana") ppAttrs.type = pp.type;
1526
+ if (pp.alignment && pp.alignment !== "left") ppAttrs.alignment = pp.alignment;
1527
+ p.push(selfCloseElement("phoneticPr", attrs(ppAttrs)));
1528
+ }
744
1529
  if (this.conditionalFormats.length > 0) for (const cf of this.conditionalFormats) {
745
1530
  p.push(`<conditionalFormatting sqref="${cf.sqref}">`);
746
1531
  for (let ri = 0; ri < cf.rules.length; ri++) {
@@ -751,7 +1536,39 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
751
1536
  };
752
1537
  if (rule.operator) ruleAttrs.operator = rule.operator;
753
1538
  if (rule.dxfId !== void 0) ruleAttrs.dxfId = rule.dxfId;
754
- if (rule.formulas && rule.formulas.length > 0) {
1539
+ if (rule.stopIfTrue) ruleAttrs.stopIfTrue = 1;
1540
+ if (rule.timePeriod) ruleAttrs.timePeriod = rule.timePeriod;
1541
+ if (rule.rank !== void 0) ruleAttrs.rank = rule.rank;
1542
+ if (rule.equalAverage) ruleAttrs.equalAverage = 1;
1543
+ if (rule.type === "colorScale" && rule.colorScale) {
1544
+ const cs = rule.colorScale;
1545
+ const inner = [];
1546
+ for (const v of cs.cfvo) inner.push(this.buildCfvoXml(v));
1547
+ for (const c of cs.colors) inner.push(`<color rgb="FF${c}"/>`);
1548
+ p.push(`<cfRule${attrs(ruleAttrs)}><colorScale>${inner.join("")}</colorScale></cfRule>`);
1549
+ } else if (rule.type === "dataBar" && rule.dataBar) {
1550
+ const db = rule.dataBar;
1551
+ const inner = [];
1552
+ for (const v of db.cfvo) inner.push(this.buildCfvoXml(v));
1553
+ inner.push(`<color rgb="FF${db.color}"/>`);
1554
+ const dbAttrs = {};
1555
+ if (db.minLength !== void 0 && db.minLength !== 10) dbAttrs.minLength = db.minLength;
1556
+ if (db.maxLength !== void 0 && db.maxLength !== 90) dbAttrs.maxLength = db.maxLength;
1557
+ if (db.showValue === false) dbAttrs.showValue = 0;
1558
+ const attrStr = Object.keys(dbAttrs).length > 0 ? attrs(dbAttrs) : "";
1559
+ p.push(`<cfRule${attrs(ruleAttrs)}><dataBar${attrStr}>${inner.join("")}</dataBar></cfRule>`);
1560
+ } else if (rule.type === "iconSet" && rule.iconSet) {
1561
+ const is = rule.iconSet;
1562
+ const inner = [];
1563
+ for (const v of is.cfvo) inner.push(this.buildCfvoXml(v));
1564
+ const isAttrs = {};
1565
+ if (is.iconSet !== void 0 && is.iconSet !== "3TrafficLights1") isAttrs.iconSet = is.iconSet;
1566
+ if (is.showValue === false) isAttrs.showValue = 0;
1567
+ if (is.percent === false) isAttrs.percent = 0;
1568
+ if (is.reverse) isAttrs.reverse = 1;
1569
+ const attrStr = Object.keys(isAttrs).length > 0 ? attrs(isAttrs) : "";
1570
+ p.push(`<cfRule${attrs(ruleAttrs)}><iconSet${attrStr}>${inner.join("")}</iconSet></cfRule>`);
1571
+ } else if (rule.formulas && rule.formulas.length > 0) {
755
1572
  const formulaParts = rule.formulas.map((f) => `<formula>${escapeXml(f)}</formula>`);
756
1573
  p.push(`<cfRule${attrs(ruleAttrs)}>`, ...formulaParts, "</cfRule>");
757
1574
  } else p.push(selfCloseElement("cfRule", attrs(ruleAttrs)));
@@ -759,7 +1576,9 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
759
1576
  p.push("</conditionalFormatting>");
760
1577
  }
761
1578
  if (this.dataValidations.length > 0) {
762
- p.push(`<dataValidations count="${this.dataValidations.length}">`);
1579
+ const dvContainerAttrs = { count: this.dataValidations.length };
1580
+ if (this.dataValidationsDisablePrompts) dvContainerAttrs.disablePrompts = 1;
1581
+ p.push(`<dataValidations${attrs(dvContainerAttrs)}>`);
763
1582
  for (const dv of this.dataValidations) {
764
1583
  const dvAttrs = { sqref: dv.sqref };
765
1584
  if (dv.type && dv.type !== "none") dvAttrs.type = dv.type;
@@ -771,6 +1590,9 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
771
1590
  if (dv.error) dvAttrs.error = dv.error;
772
1591
  if (dv.promptTitle) dvAttrs.promptTitle = dv.promptTitle;
773
1592
  if (dv.prompt) dvAttrs.prompt = dv.prompt;
1593
+ if (dv.errorStyle) dvAttrs.errorStyle = dv.errorStyle;
1594
+ if (dv.imeMode) dvAttrs.imeMode = dv.imeMode;
1595
+ if (dv.showDropDown) dvAttrs.showDropDown = 1;
774
1596
  const inner = [];
775
1597
  if (dv.formula1 !== void 0) inner.push(`<formula1>${escapeXml(dv.formula1)}</formula1>`);
776
1598
  if (dv.formula2 !== void 0) inner.push(`<formula2>${escapeXml(dv.formula2)}</formula2>`);
@@ -794,6 +1616,16 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
794
1616
  }
795
1617
  p.push("</hyperlinks>");
796
1618
  }
1619
+ if (this.printOptions) {
1620
+ const po = this.printOptions;
1621
+ const poAttrs = {};
1622
+ if (po.horizontalCentered) poAttrs.horizontalCentered = 1;
1623
+ if (po.verticalCentered) poAttrs.verticalCentered = 1;
1624
+ if (po.headings) poAttrs.headings = 1;
1625
+ if (po.gridLines) poAttrs.gridLines = 1;
1626
+ if (po.gridLinesSet === false) poAttrs.gridLinesSet = 0;
1627
+ p.push(selfCloseElement("printOptions", attrs(poAttrs)));
1628
+ }
797
1629
  p.push("<pageMargins left=\"0.75\" right=\"0.75\" top=\"1\" bottom=\"1\" header=\"0.5\" footer=\"0.5\"/>");
798
1630
  if (this.pageSetup) {
799
1631
  const ps = this.pageSetup;
@@ -806,6 +1638,13 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
806
1638
  if (ps.pageOrder && ps.pageOrder !== "downThenOver") psAttrs.pageOrder = ps.pageOrder;
807
1639
  if (ps.useFirstPageNumber) psAttrs.useFirstPageNumber = 1;
808
1640
  if (ps.firstPageNumber !== void 0) psAttrs.firstPageNumber = ps.firstPageNumber;
1641
+ if (ps.paperHeight !== void 0) psAttrs.paperHeight = ps.paperHeight;
1642
+ if (ps.paperWidth !== void 0) psAttrs.paperWidth = ps.paperWidth;
1643
+ if (ps.usePrinterDefaults) psAttrs.usePrinterDefaults = 1;
1644
+ if (ps.blackAndWhite) psAttrs.blackAndWhite = 1;
1645
+ if (ps.draft) psAttrs.draft = 1;
1646
+ if (ps.cellComments && ps.cellComments !== "none") psAttrs.cellComments = ps.cellComments;
1647
+ if (ps.errors && ps.errors !== "displayed") psAttrs.errors = ps.errors;
809
1648
  p.push(selfCloseElement("pageSetup", attrs(psAttrs)));
810
1649
  }
811
1650
  if (this.headerFooter) {
@@ -813,6 +1652,8 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
813
1652
  const hfAttrs = {};
814
1653
  if (hf.differentOddEven) hfAttrs.differentOddEven = 1;
815
1654
  if (hf.differentFirst) hfAttrs.differentFirst = 1;
1655
+ if (hf.scaleWithDoc === false) hfAttrs.scaleWithDoc = 0;
1656
+ if (hf.alignWithMargins === false) hfAttrs.alignWithMargins = 0;
816
1657
  const inner = [];
817
1658
  if (hf.oddHeader) inner.push(`<oddHeader>${escapeXml(hf.oddHeader)}</oddHeader>`);
818
1659
  if (hf.oddFooter) inner.push(`<oddFooter>${escapeXml(hf.oddFooter)}</oddFooter>`);
@@ -823,9 +1664,129 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
823
1664
  if (inner.length > 0) p.push(`<headerFooter${attrs(hfAttrs)}>`, ...inner, "</headerFooter>");
824
1665
  else if (hfAttrs.differentOddEven || hfAttrs.differentFirst) p.push(selfCloseElement("headerFooter", attrs(hfAttrs)));
825
1666
  }
1667
+ if (this.drawingHF) {
1668
+ const dhf = this.drawingHF;
1669
+ const dhfAttrs = { "r:id": dhf.rId };
1670
+ if (dhf.lho !== void 0) dhfAttrs.lho = dhf.lho;
1671
+ if (dhf.lhe !== void 0) dhfAttrs.lhe = dhf.lhe;
1672
+ if (dhf.lhf !== void 0) dhfAttrs.lhf = dhf.lhf;
1673
+ if (dhf.cho !== void 0) dhfAttrs.cho = dhf.cho;
1674
+ if (dhf.che !== void 0) dhfAttrs.che = dhf.che;
1675
+ if (dhf.chf !== void 0) dhfAttrs.chf = dhf.chf;
1676
+ if (dhf.rho !== void 0) dhfAttrs.rho = dhf.rho;
1677
+ if (dhf.rhe !== void 0) dhfAttrs.rhe = dhf.rhe;
1678
+ if (dhf.rhf !== void 0) dhfAttrs.rhf = dhf.rhf;
1679
+ if (dhf.lfo !== void 0) dhfAttrs.lfo = dhf.lfo;
1680
+ if (dhf.lfe !== void 0) dhfAttrs.lfe = dhf.lfe;
1681
+ if (dhf.lff !== void 0) dhfAttrs.lff = dhf.lff;
1682
+ if (dhf.cfo !== void 0) dhfAttrs.cfo = dhf.cfo;
1683
+ if (dhf.cfe !== void 0) dhfAttrs.cfe = dhf.cfe;
1684
+ if (dhf.cff !== void 0) dhfAttrs.cff = dhf.cff;
1685
+ if (dhf.rfo !== void 0) dhfAttrs.rfo = dhf.rfo;
1686
+ if (dhf.rfe !== void 0) dhfAttrs.rfe = dhf.rfe;
1687
+ if (dhf.rff !== void 0) dhfAttrs.rff = dhf.rff;
1688
+ p.push(selfCloseElement("drawingHF", attrs(dhfAttrs)));
1689
+ }
1690
+ if (this.legacyDrawingHF) p.push(`<legacyDrawingHF r:id="${escapeXml(this.legacyDrawingHF)}"/>`);
1691
+ if (this.ignoredErrors.length > 0) {
1692
+ const ieParts = ["<ignoredErrors>"];
1693
+ for (const ie of this.ignoredErrors) {
1694
+ const ieAttrs = { sqref: ie.sqref };
1695
+ if (ie.evalError) ieAttrs.evalError = 1;
1696
+ if (ie.twoDigitTextYear) ieAttrs.twoDigitTextYear = 1;
1697
+ if (ie.numberStoredAsText) ieAttrs.numberStoredAsText = 1;
1698
+ if (ie.formula) ieAttrs.formula = 1;
1699
+ if (ie.formulaRange) ieAttrs.formulaRange = 1;
1700
+ if (ie.unlockedFormula) ieAttrs.unlockedFormula = 1;
1701
+ if (ie.emptyCellReference) ieAttrs.emptyCellReference = 1;
1702
+ if (ie.listDataValidation) ieAttrs.listDataValidation = 1;
1703
+ if (ie.calculatedColumn) ieAttrs.calculatedColumn = 1;
1704
+ ieParts.push(selfCloseElement("ignoredError", attrs(ieAttrs)));
1705
+ }
1706
+ ieParts.push("</ignoredErrors>");
1707
+ p.push(ieParts.join(""));
1708
+ }
1709
+ if (this.backgroundImage) p.push("<!--BACKGROUND_PICTURE-->");
1710
+ if (this.oleObjects.length > 0) {
1711
+ const oleParts = ["<oleObjects>"];
1712
+ for (const ole of this.oleObjects) {
1713
+ const oleAttrs = [`shapeId="${ole.shapeId}"`];
1714
+ if (ole.progId) oleAttrs.push(`progId="${escapeXml(ole.progId)}"`);
1715
+ if (ole.dvAspect && ole.dvAspect !== "DVASPECT_CONTENT") oleAttrs.push(`dvAspect="${ole.dvAspect}"`);
1716
+ if (ole.link) oleAttrs.push(`link="${escapeXml(ole.link)}"`);
1717
+ if (ole.oleUpdate) oleAttrs.push(`oleUpdate="${ole.oleUpdate}"`);
1718
+ if (ole.autoLoad) oleAttrs.push("autoLoad=\"1\"");
1719
+ if (ole.rId) oleAttrs.push(`r:id="${escapeXml(ole.rId)}"`);
1720
+ if (ole.objectPr) {
1721
+ const opr = ole.objectPr;
1722
+ const oprAttrs = [];
1723
+ if (opr.locked === false) oprAttrs.push("locked=\"0\"");
1724
+ if (opr.defaultSize === false) oprAttrs.push("defaultSize=\"0\"");
1725
+ if (opr.print === false) oprAttrs.push("print=\"0\"");
1726
+ if (opr.disabled) oprAttrs.push("disabled=\"1\"");
1727
+ if (opr.uiObject) oprAttrs.push("uiObject=\"1\"");
1728
+ if (opr.autoFill === false) oprAttrs.push("autoFill=\"0\"");
1729
+ if (opr.autoLine === false) oprAttrs.push("autoLine=\"0\"");
1730
+ if (opr.autoPict === false) oprAttrs.push("autoPict=\"0\"");
1731
+ if (opr.macro) oprAttrs.push(`macro="${escapeXml(opr.macro)}"`);
1732
+ if (opr.altText) oprAttrs.push(`altText="${escapeXml(opr.altText)}"`);
1733
+ if (opr.dde) oprAttrs.push("dde=\"1\"");
1734
+ if (opr.rId) oprAttrs.push(`r:id="${escapeXml(opr.rId)}"`);
1735
+ oleParts.push(`<oleObject ${oleAttrs.join(" ")}><objectPr${oprAttrs.length ? " " + oprAttrs.join(" ") : ""}/></oleObject>`);
1736
+ } else oleParts.push(`<oleObject ${oleAttrs.join(" ")}/>`);
1737
+ }
1738
+ oleParts.push("</oleObjects>");
1739
+ p.push(oleParts.join(""));
1740
+ }
1741
+ if (this.controls.length > 0) {
1742
+ const ctrlParts = ["<controls>"];
1743
+ for (const c of this.controls) {
1744
+ const cAttrs = [`shapeId="${c.shapeId}"`, `r:id="${escapeXml(c.rId)}"`];
1745
+ if (c.name) cAttrs.push(`name="${escapeXml(c.name)}"`);
1746
+ const prAttrs = [];
1747
+ if (c.locked === false) prAttrs.push("locked=\"0\"");
1748
+ if (c.uiObject) prAttrs.push("uiObject=\"1\"");
1749
+ if (c.recalcAlways) prAttrs.push("recalcAlways=\"1\"");
1750
+ if (c.linkedCell) prAttrs.push(`linkedCell="${escapeXml(c.linkedCell)}"`);
1751
+ if (c.listFillRange) prAttrs.push(`listFillRange="${escapeXml(c.listFillRange)}"`);
1752
+ if (c.cf) prAttrs.push(`cf="${escapeXml(c.cf)}"`);
1753
+ if (prAttrs.length > 0) ctrlParts.push(`<control ${cAttrs.join(" ")}><controlPr${prAttrs.length ? " " + prAttrs.join(" ") : ""}/></control>`);
1754
+ else ctrlParts.push(`<control ${cAttrs.join(" ")}/>`);
1755
+ }
1756
+ ctrlParts.push("</controls>");
1757
+ p.push(ctrlParts.join(""));
1758
+ }
1759
+ if (this.webPublishItems.length > 0) {
1760
+ const wpParts = [`<webPublishItems count="${this.webPublishItems.length}">`];
1761
+ for (const wpi of this.webPublishItems) {
1762
+ const wpiAttrs = [
1763
+ `id="${wpi.id}"`,
1764
+ `divId="${escapeXml(wpi.divId)}"`,
1765
+ `sourceType="${wpi.sourceType}"`,
1766
+ `destinationFile="${escapeXml(wpi.destinationFile)}"`
1767
+ ];
1768
+ if (wpi.sourceRef) wpiAttrs.push(`sourceRef="${escapeXml(wpi.sourceRef)}"`);
1769
+ if (wpi.sourceObject) wpiAttrs.push(`sourceObject="${escapeXml(wpi.sourceObject)}"`);
1770
+ if (wpi.title) wpiAttrs.push(`title="${escapeXml(wpi.title)}"`);
1771
+ if (wpi.autoRepublish) wpiAttrs.push("autoRepublish=\"1\"");
1772
+ wpParts.push(`<webPublishItem ${wpiAttrs.join(" ")}/>`);
1773
+ }
1774
+ wpParts.push("</webPublishItems>");
1775
+ p.push(wpParts.join(""));
1776
+ }
1777
+ if (this.ext) p.push(`<extLst>${this.ext}</extLst>`);
826
1778
  p.push("</worksheet>");
827
1779
  return p.join("");
828
1780
  }
1781
+ /**
1782
+ * Build a <cfvo> element string for conditional formatting.
1783
+ */
1784
+ buildCfvoXml(cfvo) {
1785
+ const a = { type: cfvo.type };
1786
+ if (cfvo.val !== void 0) a.val = cfvo.val;
1787
+ if (cfvo.gte === false) a.gte = 0;
1788
+ return `<cfvo${attrs(a)}/>`;
1789
+ }
829
1790
  buildSheetViewAttrs() {
830
1791
  const sv = this.sheetView;
831
1792
  const svMap = { workbookViewId: 0 };
@@ -836,8 +1797,48 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
836
1797
  if (sv?.showZeros === false) svMap.showZeros = 0;
837
1798
  if (sv?.zoomScale !== void 0) svMap.zoomScale = sv.zoomScale;
838
1799
  if (sv?.rightToLeft) svMap.rightToLeft = 1;
1800
+ if (sv?.windowProtection) svMap.windowProtection = 1;
1801
+ if (sv?.showFormulas) svMap.showFormulas = 1;
1802
+ if (sv?.showRuler === false) svMap.showRuler = 0;
1803
+ if (sv?.showOutlineSymbols === false) svMap.showOutlineSymbols = 0;
1804
+ if (sv?.defaultGridColor === false) svMap.defaultGridColor = 0;
1805
+ if (sv?.showWhiteSpace === false) svMap.showWhiteSpace = 0;
1806
+ if (sv?.view) svMap.view = sv.view;
1807
+ if (sv?.colorId !== void 0) svMap.colorId = sv.colorId;
1808
+ if (sv?.zoomScaleNormal !== void 0) svMap.zoomScaleNormal = sv.zoomScaleNormal;
1809
+ if (sv?.zoomScaleSheetLayoutView !== void 0) svMap.zoomScaleSheetLayoutView = sv.zoomScaleSheetLayoutView;
1810
+ if (sv?.zoomScalePageLayoutView !== void 0) svMap.zoomScalePageLayoutView = sv.zoomScalePageLayoutView;
839
1811
  return attrs(svMap);
840
1812
  }
1813
+ buildSelectionXml(sel) {
1814
+ const selAttrs = {};
1815
+ if (sel.pane) selAttrs.pane = sel.pane;
1816
+ if (sel.activeCell) selAttrs.activeCell = sel.activeCell;
1817
+ if (sel.activeCellId !== void 0) selAttrs.activeCellId = sel.activeCellId;
1818
+ if (sel.sqref) selAttrs.sqref = sel.sqref;
1819
+ return `<selection${attrs(selAttrs)}/>`;
1820
+ }
1821
+ buildPivotSelectionXml(ps) {
1822
+ const psAttrs = {};
1823
+ if (ps.pane) psAttrs.pane = ps.pane;
1824
+ if (ps.showHeader) psAttrs.showHeader = 1;
1825
+ if (ps.label) psAttrs.label = 1;
1826
+ if (ps.data) psAttrs.data = 1;
1827
+ if (ps.extendable) psAttrs.extendable = 1;
1828
+ if (ps.count !== void 0) psAttrs.count = ps.count;
1829
+ if (ps.axis) psAttrs.axis = ps.axis;
1830
+ if (ps.dimension !== void 0) psAttrs.dimension = ps.dimension;
1831
+ if (ps.start !== void 0) psAttrs.start = ps.start;
1832
+ if (ps.min !== void 0) psAttrs.min = ps.min;
1833
+ if (ps.max !== void 0) psAttrs.max = ps.max;
1834
+ if (ps.activeRow !== void 0) psAttrs.activeRow = ps.activeRow;
1835
+ if (ps.activeCol !== void 0) psAttrs.activeCol = ps.activeCol;
1836
+ if (ps.previousRow !== void 0) psAttrs.previousRow = ps.previousRow;
1837
+ if (ps.previousCol !== void 0) psAttrs.previousCol = ps.previousCol;
1838
+ if (ps.click !== void 0) psAttrs.click = ps.click;
1839
+ if (ps.rId) psAttrs["r:id"] = ps.rId;
1840
+ return `<pivotSelection${attrs(psAttrs)}><pivotArea/></pivotSelection>`;
1841
+ }
841
1842
  /**
842
1843
  * Excel legacy password hash (16-bit, little-endian hex).
843
1844
  * Matches the algorithm used by ECMA-376 Part 1, §18.2.27.
@@ -863,6 +1864,15 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
863
1864
  if (fOpts.type && fOpts.type !== FormulaType.NORMAL) fAttrs.t = fOpts.type;
864
1865
  if (fOpts.reference) fAttrs.ref = fOpts.reference;
865
1866
  if (fOpts.sharedIndex !== void 0) fAttrs.si = fOpts.sharedIndex;
1867
+ if (fOpts.aca) fAttrs.aca = 1;
1868
+ if (fOpts.dt2D) fAttrs.dt2D = 1;
1869
+ if (fOpts.dtr) fAttrs.dtr = 1;
1870
+ if (fOpts.del1) fAttrs.del1 = 1;
1871
+ if (fOpts.del2) fAttrs.del2 = 1;
1872
+ if (fOpts.r1) fAttrs.r1 = fOpts.r1;
1873
+ if (fOpts.r2) fAttrs.r2 = fOpts.r2;
1874
+ if (fOpts.ca) fAttrs.ca = 1;
1875
+ if (fOpts.bx) fAttrs.bx = 1;
866
1876
  if (fOpts.formula !== void 0 && fOpts.formula !== "") return `<f${attrs(fAttrs)}>${escapeXml(fOpts.formula)}</f>`;
867
1877
  if (Object.keys(fAttrs).length > 0) return selfCloseElement("f", attrs(fAttrs));
868
1878
  return "";
@@ -894,6 +1904,15 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
894
1904
  if (cell.styleIndex !== void 0) return selfCloseElement("c", attrs(cellAttrs));
895
1905
  return "";
896
1906
  }
1907
+ if (typeof value === "object" && !(value instanceof Date)) {
1908
+ if (sharedStrings) {
1909
+ cellAttrs.t = "s";
1910
+ const idx = sharedStrings.registerRich(value);
1911
+ return `<c${attrs(cellAttrs)}><v>${idx}</v></c>`;
1912
+ }
1913
+ cellAttrs.t = "inlineStr";
1914
+ return `<c${attrs(cellAttrs)}><is>${buildRstXml(value)}</is></c>`;
1915
+ }
897
1916
  if (typeof value === "string") {
898
1917
  if (sharedStrings) {
899
1918
  cellAttrs.t = "s";
@@ -941,8 +1960,18 @@ var Worksheet = class extends IgnoreIfEmptyXmlComponent {
941
1960
  */
942
1961
  var File = class {
943
1962
  worksheetOptions;
1963
+ chartsheetOptions;
944
1964
  corePropsOptions;
945
1965
  dxfOptions;
1966
+ protectionOptions;
1967
+ externalLinkOptions;
1968
+ customViewOptions;
1969
+ fileRecoveryPrOpts;
1970
+ functionGroupOpts;
1971
+ webPublishingOpts;
1972
+ fileSharingOpts;
1973
+ volTypeOpts;
1974
+ webPublishObjectOpts;
946
1975
  _coreProperties;
947
1976
  _appProperties;
948
1977
  _contentTypes;
@@ -958,8 +1987,18 @@ var File = class {
958
1987
  _pivotCacheRefs = [];
959
1988
  constructor(options) {
960
1989
  this.worksheetOptions = options.worksheets ?? [];
1990
+ this.chartsheetOptions = options.chartsheets ?? [];
961
1991
  this.corePropsOptions = options;
962
1992
  this.dxfOptions = options.dxfs ?? [];
1993
+ this.protectionOptions = options.workbookProtection;
1994
+ this.externalLinkOptions = options.externalLinks ?? [];
1995
+ this.customViewOptions = options.customWorkbookViews;
1996
+ this.fileRecoveryPrOpts = options.fileRecoveryPr;
1997
+ this.functionGroupOpts = options.functionGroups;
1998
+ this.webPublishingOpts = options.webPublishing;
1999
+ this.fileSharingOpts = options.fileSharing;
2000
+ this.volTypeOpts = options.volTypes;
2001
+ this.webPublishObjectOpts = options.webPublishObjects;
963
2002
  }
964
2003
  get coreProperties() {
965
2004
  return this._coreProperties ??= new CoreProperties(this.corePropsOptions);
@@ -992,12 +2031,20 @@ var File = class {
992
2031
  }
993
2032
  get workbookXml() {
994
2033
  if (!this._workbookXml) {
995
- const sheets = this.worksheetOptions.map((ws, i) => ({
996
- name: ws.name ?? `Sheet${i + 1}`,
997
- sheetId: i + 1,
998
- rId: `rId${i + 1}`
999
- }));
1000
- this._workbookXml = new WorkbookXml(sheets, this._pivotCacheRefs);
2034
+ const sheets = [];
2035
+ let sheetId = 1;
2036
+ let rId = 1;
2037
+ for (const ws of this.worksheetOptions) sheets.push({
2038
+ name: ws.name ?? `Sheet${sheetId}`,
2039
+ sheetId: sheetId++,
2040
+ rId: `rId${rId++}`
2041
+ });
2042
+ for (const cs of this.chartsheetOptions) sheets.push({
2043
+ name: cs.name ?? `Chart${sheetId}`,
2044
+ sheetId: sheetId++,
2045
+ rId: `rId${rId++}`
2046
+ });
2047
+ this._workbookXml = new WorkbookXml(sheets, this._pivotCacheRefs, this.protectionOptions, this.customViewOptions, this.fileRecoveryPrOpts, this.functionGroupOpts, this.webPublishingOpts, this.fileSharingOpts, void 0, void 0, void 0, this.volTypeOpts, this.webPublishObjectOpts);
1001
2048
  }
1002
2049
  return this._workbookXml;
1003
2050
  }
@@ -1022,9 +2069,15 @@ var File = class {
1022
2069
  rId
1023
2070
  });
1024
2071
  }
2072
+ get externalLinks() {
2073
+ return this.externalLinkOptions;
2074
+ }
1025
2075
  get worksheetConfigs() {
1026
2076
  return this.worksheetOptions;
1027
2077
  }
2078
+ get chartsheetConfigs() {
2079
+ return this.chartsheetOptions;
2080
+ }
1028
2081
  get worksheets() {
1029
2082
  if (!this._worksheets) this._worksheets = this.worksheetOptions.map((ws) => new Worksheet(ws));
1030
2083
  return this._worksheets;
@@ -1043,6 +2096,7 @@ var File = class {
1043
2096
  this._workbookRels = new Relationships();
1044
2097
  let rid = 1;
1045
2098
  for (let i = 0; i < this.worksheetOptions.length; i++) this._workbookRels.addRelationship(rid++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", `worksheets/sheet${i + 1}.xml`);
2099
+ for (let i = 0; i < this.chartsheetOptions.length; i++) this._workbookRels.addRelationship(rid++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet", `chartsheets/sheet${i + 1}.xml`);
1046
2100
  this._workbookRels.addRelationship(rid++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles", "styles.xml");
1047
2101
  this._workbookRels.addRelationship(rid++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", "theme/theme1.xml");
1048
2102
  this._workbookRels.addRelationship(rid++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings", "sharedStrings.xml");
@@ -1051,79 +2105,76 @@ var File = class {
1051
2105
  }
1052
2106
  };
1053
2107
  //#endregion
1054
- //#region src/file/comments.ts
1055
- /**
1056
- * Generates xl/comments{n}.xml — cell comment data.
1057
- *
1058
- * @module
1059
- */
1060
- var Comments = class extends BaseXmlComponent {
1061
- entries;
1062
- constructor(entries) {
1063
- super("comments");
1064
- this.entries = entries;
1065
- }
1066
- toXml(_context) {
1067
- const authors = this.collectAuthors();
1068
- const p = ["<comments xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">", `<authors>`];
1069
- for (const author of authors) p.push(`<author>${escapeXml(author)}</author>`);
1070
- p.push("</authors><commentList>");
1071
- for (const entry of this.entries) {
1072
- const authorId = authors.indexOf(entry.author);
1073
- p.push(`<comment ref="${entry.cell}" authorId="${authorId}"><text><t>${escapeXml(entry.text)}</t></text></comment>`);
1074
- }
1075
- p.push("</commentList></comments>");
1076
- return p.join("");
1077
- }
1078
- collectAuthors() {
1079
- const seen = /* @__PURE__ */ new Set();
1080
- const result = [];
1081
- for (const entry of this.entries) if (!seen.has(entry.author)) {
1082
- seen.add(entry.author);
1083
- result.push(entry.author);
1084
- }
1085
- return result.length > 0 ? result : [""];
1086
- }
1087
- };
1088
- //#endregion
1089
- //#region src/file/drawing/drawing.ts
1090
- /**
1091
- * XLSX Drawing component — generates xl/drawings/drawing{n}.xml.
1092
- *
1093
- * Uses the spreadsheetDrawing namespace (default, no prefix) for anchoring
1094
- * images and charts to worksheet cells.
1095
- *
1096
- * @module
1097
- */
1098
- const XDR_NS = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing";
1099
- const A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main";
1100
- const R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
1101
- const C_URI = "http://schemas.openxmlformats.org/drawingml/2006/chart";
1102
- var Drawing = class extends BaseXmlComponent {
1103
- images;
1104
- charts;
1105
- constructor(images, charts = []) {
1106
- super("wsDr");
1107
- this.images = images;
1108
- this.charts = charts;
1109
- }
1110
- toXml(_context) {
1111
- const p = [`<wsDr xmlns="${XDR_NS}" xmlns:a="${A_NS}" xmlns:r="${R_NS}">`];
1112
- let id = 1;
1113
- for (const img of this.images) {
1114
- p.push(`<twoCellAnchor editAs="oneCell"><from><col>${img.col - 1}</col><colOff>${img.colOffset ?? 0}</colOff><row>${img.row - 1}</row><rowOff>${img.rowOffset ?? 0}</rowOff></from>`, `<to><col>${img.col}</col><colOff>0</colOff><row>${img.row}</row><rowOff>0</rowOff></to>`, `<pic><nvPicPr><cNvPr id="${id}" name="Picture ${id}"/><cNvPicPr preferRelativeResize="1"/></nvPicPr>`, `<blipFill><a:blip r:embed="${img.rId}"/><a:stretch><a:fillRect/></a:stretch></blipFill>`, `<spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="400000" cy="300000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></spPr></pic>`, `<clientData/></twoCellAnchor>`);
1115
- id++;
1116
- }
1117
- for (const chart of this.charts) {
1118
- p.push(`<twoCellAnchor editAs="oneCell"><from><col>${chart.col - 1}</col><colOff>${chart.colOffset ?? 0}</colOff><row>${chart.row - 1}</row><rowOff>${chart.rowOffset ?? 0}</rowOff></from>`, `<to><col>${chart.col + 8}</col><colOff>0</colOff><row>${chart.row + 15}</row><rowOff>0</rowOff></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}" r:id="${chart.rId}"/></a:graphicData></a:graphic></graphicFrame>`, `<clientData/></twoCellAnchor>`);
1119
- id++;
1120
- }
1121
- p.push("</wsDr>");
1122
- return p.join("");
1123
- }
1124
- };
1125
- //#endregion
1126
2108
  //#region src/file/pivot/pivot-utils.ts
2109
+ /** Pivot filter type (ST_PivotFilterType) */
2110
+ const PivotFilterType = {
2111
+ UNKNOWN: "unknown",
2112
+ COUNT: "count",
2113
+ PERCENT: "percent",
2114
+ SUM: "sum",
2115
+ CAPTION_EQUAL: "captionEqual",
2116
+ CAPTION_NOT_EQUAL: "captionNotEqual",
2117
+ CAPTION_BEGINS_WITH: "captionBeginsWith",
2118
+ CAPTION_NOT_BEGINS_WITH: "captionNotBeginsWith",
2119
+ CAPTION_ENDS_WITH: "captionEndsWith",
2120
+ CAPTION_NOT_ENDS_WITH: "captionNotEndsWith",
2121
+ CAPTION_CONTAINS: "captionContains",
2122
+ CAPTION_NOT_CONTAINS: "captionNotContains",
2123
+ CAPTION_GREATER_THAN: "captionGreaterThan",
2124
+ CAPTION_GREATER_THAN_OR_EQUAL: "captionGreaterThanOrEqual",
2125
+ CAPTION_LESS_THAN: "captionLessThan",
2126
+ CAPTION_LESS_THAN_OR_EQUAL: "captionLessThanOrEqual",
2127
+ CAPTION_BETWEEN: "captionBetween",
2128
+ CAPTION_NOT_BETWEEN: "captionNotBetween",
2129
+ VALUE_EQUAL: "valueEqual",
2130
+ VALUE_NOT_EQUAL: "valueNotEqual",
2131
+ VALUE_GREATER_THAN: "valueGreaterThan",
2132
+ VALUE_GREATER_THAN_OR_EQUAL: "valueGreaterThanOrEqual",
2133
+ VALUE_LESS_THAN: "valueLessThan",
2134
+ VALUE_LESS_THAN_OR_EQUAL: "valueLessThanOrEqual",
2135
+ VALUE_BETWEEN: "valueBetween",
2136
+ VALUE_NOT_BETWEEN: "valueNotBetween",
2137
+ DATE_EQUAL: "dateEqual",
2138
+ DATE_NOT_EQUAL: "dateNotEqual",
2139
+ DATE_OLDER_THAN: "dateOlderThan",
2140
+ DATE_OLDER_THAN_OR_EQUAL: "dateOlderThanOrEqual",
2141
+ DATE_NEWER_THAN: "dateNewerThan",
2142
+ DATE_NEWER_THAN_OR_EQUAL: "dateNewerThanOrEqual",
2143
+ DATE_BETWEEN: "dateBetween",
2144
+ DATE_NOT_BETWEEN: "dateNotBetween",
2145
+ TOMORROW: "tomorrow",
2146
+ TODAY: "today",
2147
+ YESTERDAY: "yesterday",
2148
+ NEXT_WEEK: "nextWeek",
2149
+ THIS_WEEK: "thisWeek",
2150
+ LAST_WEEK: "lastWeek",
2151
+ NEXT_MONTH: "nextMonth",
2152
+ THIS_MONTH: "thisMonth",
2153
+ LAST_MONTH: "lastMonth",
2154
+ NEXT_QUARTER: "nextQuarter",
2155
+ THIS_QUARTER: "thisQuarter",
2156
+ LAST_QUARTER: "lastQuarter",
2157
+ NEXT_YEAR: "nextYear",
2158
+ THIS_YEAR: "thisYear",
2159
+ LAST_YEAR: "lastYear",
2160
+ YEAR_TO_DATE: "yearToDate",
2161
+ Q1: "Q1",
2162
+ Q2: "Q2",
2163
+ Q3: "Q3",
2164
+ Q4: "Q4",
2165
+ M1: "M1",
2166
+ M2: "M2",
2167
+ M3: "M3",
2168
+ M4: "M4",
2169
+ M5: "M5",
2170
+ M6: "M6",
2171
+ M7: "M7",
2172
+ M8: "M8",
2173
+ M9: "M9",
2174
+ M10: "M10",
2175
+ M11: "M11",
2176
+ M12: "M12"
2177
+ };
1127
2178
  /**
1128
2179
  * Extract unique values from source data for a given field index.
1129
2180
  */
@@ -1132,7 +2183,7 @@ function collectUniqueValues(records, fieldIdx) {
1132
2183
  const result = [];
1133
2184
  for (const row of records) {
1134
2185
  const val = row[fieldIdx];
1135
- const key = String(val);
2186
+ const key = val instanceof Date ? val.toISOString() : String(val);
1136
2187
  if (!seen.has(key)) {
1137
2188
  seen.add(key);
1138
2189
  result.push(val);
@@ -1194,17 +2245,75 @@ var PivotCacheDefinitionXml = class extends BaseXmlComponent {
1194
2245
  sourceSheet;
1195
2246
  sourceData;
1196
2247
  recordsRid;
1197
- constructor(_cacheIdx, sourceRef, sourceSheet, sourceData, recordsRid) {
2248
+ olapPr;
2249
+ cacheDefOpts;
2250
+ constructor(_cacheIdx, sourceRef, sourceSheet, sourceData, recordsRid, olapPr, cacheDefOpts) {
1198
2251
  super("pivotCacheDefinition");
1199
2252
  this.sourceRef = sourceRef;
1200
2253
  this.sourceSheet = sourceSheet;
1201
2254
  this.sourceData = sourceData;
1202
2255
  this.recordsRid = recordsRid;
2256
+ this.olapPr = olapPr;
2257
+ this.cacheDefOpts = cacheDefOpts;
1203
2258
  }
1204
2259
  toXml(_context) {
1205
2260
  const p = [];
1206
- p.push(`<pivotCacheDefinition xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:id="${escapeXml(this.recordsRid)}" recordCount="${this.sourceData.records.length}" createdVersion="6" refreshedVersion="6" minRefreshableVersion="3">`);
1207
- p.push(`<cacheSource type="worksheet"><worksheetSource ref="${escapeXml(this.sourceRef)}" sheet="${escapeXml(this.sourceSheet)}"/></cacheSource>`);
2261
+ const rootAttrs = [
2262
+ "xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"",
2263
+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"",
2264
+ `r:id="${escapeXml(this.recordsRid)}"`,
2265
+ `recordCount="${this.sourceData.records.length}"`,
2266
+ "createdVersion=\"6\"",
2267
+ "refreshedVersion=\"6\"",
2268
+ "minRefreshableVersion=\"3\""
2269
+ ];
2270
+ if (this.cacheDefOpts) {
2271
+ const cd = this.cacheDefOpts;
2272
+ if (cd.invalid) rootAttrs.push("invalid=\"1\"");
2273
+ if (cd.saveData === false) rootAttrs.push("saveData=\"0\"");
2274
+ if (cd.optimizeMemory) rootAttrs.push("optimizeMemory=\"1\"");
2275
+ if (cd.enableRefresh === false) rootAttrs.push("enableRefresh=\"0\"");
2276
+ if (cd.refreshedBy) rootAttrs.push(`refreshedBy="${escapeXml(cd.refreshedBy)}"`);
2277
+ if (cd.refreshedDate !== void 0) rootAttrs.push(`refreshedDate="${cd.refreshedDate}"`);
2278
+ if (cd.refreshedDateIso) rootAttrs.push(`refreshedDateIso="${escapeXml(cd.refreshedDateIso)}"`);
2279
+ if (cd.backgroundQuery) rootAttrs.push("backgroundQuery=\"1\"");
2280
+ if (cd.missingItemsLimit !== void 0) rootAttrs.push(`missingItemsLimit="${cd.missingItemsLimit}"`);
2281
+ if (cd.upgradeOnRefresh) rootAttrs.push("upgradeOnRefresh=\"1\"");
2282
+ if (cd.supportSubquery) rootAttrs.push("supportSubquery=\"1\"");
2283
+ if (cd.supportAdvancedDrill) rootAttrs.push("supportAdvancedDrill=\"1\"");
2284
+ }
2285
+ p.push(`<pivotCacheDefinition ${rootAttrs.join(" ")}>`);
2286
+ if (this.cacheDefOpts?.consolidation) {
2287
+ const con = this.cacheDefOpts.consolidation;
2288
+ const conParts = ["<cacheSource type=\"consolidation\"><consolidation"];
2289
+ if (con.autoPage === false) conParts.push(" autoPage=\"0\"");
2290
+ conParts.push(">");
2291
+ if (con.pages && con.pages.length > 0) {
2292
+ conParts.push(`<pages count="${con.pages.length}">`);
2293
+ for (const pg of con.pages) {
2294
+ const pgItems = pg.items ?? [];
2295
+ conParts.push(`<page${pgItems.length ? ` count="${pgItems.length}"` : ""}>`);
2296
+ for (const pi of pgItems) conParts.push(`<pageItem name="${escapeXml(pi.name)}"/>`);
2297
+ conParts.push("</page>");
2298
+ }
2299
+ conParts.push("</pages>");
2300
+ }
2301
+ conParts.push(`<rangeSets count="${con.rangeSets.length}">`);
2302
+ for (const rs of con.rangeSets) {
2303
+ const rsAttrs = [];
2304
+ if (rs.i1 !== void 0) rsAttrs.push(`i1="${rs.i1}"`);
2305
+ if (rs.i2 !== void 0) rsAttrs.push(`i2="${rs.i2}"`);
2306
+ if (rs.i3 !== void 0) rsAttrs.push(`i3="${rs.i3}"`);
2307
+ if (rs.i4 !== void 0) rsAttrs.push(`i4="${rs.i4}"`);
2308
+ if (rs.ref) rsAttrs.push(`ref="${escapeXml(rs.ref)}"`);
2309
+ if (rs.name) rsAttrs.push(`name="${escapeXml(rs.name)}"`);
2310
+ if (rs.sheet) rsAttrs.push(`sheet="${escapeXml(rs.sheet)}"`);
2311
+ if (rs.rId) rsAttrs.push(`r:id="${escapeXml(rs.rId)}"`);
2312
+ conParts.push(`<rangeSet ${rsAttrs.join(" ")}/>`);
2313
+ }
2314
+ conParts.push("</rangeSets></consolidation></cacheSource>");
2315
+ p.push(conParts.join(""));
2316
+ } else p.push(`<cacheSource type="worksheet"><worksheetSource ref="${escapeXml(this.sourceRef)}" sheet="${escapeXml(this.sourceSheet)}"/></cacheSource>`);
1208
2317
  const fields = this.sourceData.fieldNames;
1209
2318
  p.push(`<cacheFields count="${fields.length}">`);
1210
2319
  for (let i = 0; i < fields.length; i++) {
@@ -1226,16 +2335,281 @@ var PivotCacheDefinitionXml = class extends BaseXmlComponent {
1226
2335
  max = 0;
1227
2336
  }
1228
2337
  const allInteger = this.sourceData.records.every((row) => typeof row[i] === "number" && Number.isInteger(row[i]));
1229
- p.push(`<cacheField name="${escapeXml(fieldName)}" numFmtId="0"><sharedItems containsSemiMixedTypes="0" containsString="0" containsNumber="1" containsInteger="${allInteger ? "1" : "0"}" minValue="${min}" maxValue="${max}" count="${uniqueVals.length}"/></cacheField>`);
2338
+ const cfOverride = this.cacheDefOpts?.cacheFieldOverrides?.get(i);
2339
+ const cfExtraAttrs = [];
2340
+ const siExtraAttrs = [];
2341
+ if (cfOverride) {
2342
+ if (cfOverride.databaseField) cfExtraAttrs.push("databaseField=\"1\"");
2343
+ if (cfOverride.level !== void 0) cfExtraAttrs.push(`level="${cfOverride.level}"`);
2344
+ if (cfOverride.mappingCount !== void 0) cfExtraAttrs.push(`mappingCount="${cfOverride.mappingCount}"`);
2345
+ if (cfOverride.memberPropertyField !== void 0) cfExtraAttrs.push(`memberPropertyField="${cfOverride.memberPropertyField}"`);
2346
+ if (cfOverride.propertyName) cfExtraAttrs.push(`propertyName="${escapeXml(cfOverride.propertyName)}"`);
2347
+ if (cfOverride.serverField) cfExtraAttrs.push("serverField=\"1\"");
2348
+ if (cfOverride.uniqueList) cfExtraAttrs.push("uniqueList=\"1\"");
2349
+ if (cfOverride.containsMixedTypes) siExtraAttrs.push("containsMixedTypes=\"1\"");
2350
+ if (cfOverride.containsNonDate) siExtraAttrs.push("containsNonDate=\"1\"");
2351
+ if (cfOverride.longText) siExtraAttrs.push("longText=\"1\"");
2352
+ if (cfOverride.maxDate) siExtraAttrs.push(`maxDate="${escapeXml(cfOverride.maxDate)}"`);
2353
+ if (cfOverride.minDate) siExtraAttrs.push(`minDate="${escapeXml(cfOverride.minDate)}"`);
2354
+ }
2355
+ 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(" ") : ""}/></cacheField>`);
1230
2356
  } else {
1231
- p.push(`<cacheField name="${escapeXml(fieldName)}" numFmtId="0"><sharedItems count="${uniqueVals.length}">`);
1232
- for (const v of uniqueVals) p.push(`<s v="${escapeXml(String(v))}"/>`);
1233
- p.push("</sharedItems></cacheField>");
1234
- }
1235
- }
1236
- p.push("</cacheFields>");
1237
- p.push("</pivotCacheDefinition>");
1238
- return p.join("");
2357
+ let hasDate = false;
2358
+ let hasMissing = false;
2359
+ for (const v of uniqueVals) {
2360
+ if (v instanceof Date) hasDate = true;
2361
+ if (v === null) hasMissing = true;
2362
+ }
2363
+ const siAttrs = [`count="${uniqueVals.length}"`];
2364
+ if (hasDate) siAttrs.push("containsDate=\"1\"");
2365
+ if (hasMissing) siAttrs.push("containsBlank=\"1\"");
2366
+ const cfOverride = this.cacheDefOpts?.cacheFieldOverrides?.get(i);
2367
+ const cfExtraAttrs = [];
2368
+ if (cfOverride) {
2369
+ if (cfOverride.databaseField) cfExtraAttrs.push("databaseField=\"1\"");
2370
+ if (cfOverride.level !== void 0) cfExtraAttrs.push(`level="${cfOverride.level}"`);
2371
+ if (cfOverride.mappingCount !== void 0) cfExtraAttrs.push(`mappingCount="${cfOverride.mappingCount}"`);
2372
+ if (cfOverride.memberPropertyField !== void 0) cfExtraAttrs.push(`memberPropertyField="${cfOverride.memberPropertyField}"`);
2373
+ if (cfOverride.propertyName) cfExtraAttrs.push(`propertyName="${escapeXml(cfOverride.propertyName)}"`);
2374
+ if (cfOverride.serverField) cfExtraAttrs.push("serverField=\"1\"");
2375
+ if (cfOverride.uniqueList) cfExtraAttrs.push("uniqueList=\"1\"");
2376
+ if (cfOverride.containsMixedTypes) siAttrs.push("containsMixedTypes=\"1\"");
2377
+ if (cfOverride.containsNonDate) siAttrs.push("containsNonDate=\"1\"");
2378
+ if (cfOverride.longText) siAttrs.push("longText=\"1\"");
2379
+ if (cfOverride.maxDate) siAttrs.push(`maxDate="${escapeXml(cfOverride.maxDate)}"`);
2380
+ if (cfOverride.minDate) siAttrs.push(`minDate="${escapeXml(cfOverride.minDate)}"`);
2381
+ }
2382
+ p.push(`<cacheField name="${escapeXml(fieldName)}" ${cfExtraAttrs.length ? cfExtraAttrs.join(" ") + " " : ""}numFmtId="0"><sharedItems ${siAttrs.join(" ")}>`);
2383
+ for (const v of uniqueVals) if (v === null) p.push("<m/>");
2384
+ else if (v instanceof Date) p.push(`<d v="${v.toISOString().replace(/\.\d{3}Z$/, "Z")}"/>`);
2385
+ else p.push(`<s v="${escapeXml(String(v))}"/>`);
2386
+ p.push("</sharedItems>");
2387
+ const fg = this.cacheDefOpts?.fieldGroups?.get(i);
2388
+ if (fg) {
2389
+ const fgParts = ["<fieldGroup"];
2390
+ if (fg.parent !== void 0) fgParts.push(` par="${fg.parent}"`);
2391
+ if (fg.base !== void 0) fgParts.push(` base="${fg.base}"`);
2392
+ fgParts.push(">");
2393
+ if (fg.rangePr) {
2394
+ const rp = fg.rangePr;
2395
+ const rpAttrs = [];
2396
+ if (rp.autoStart === false) rpAttrs.push("autoStart=\"0\"");
2397
+ if (rp.autoEnd === false) rpAttrs.push("autoEnd=\"0\"");
2398
+ if (rp.groupBy && rp.groupBy !== "range") rpAttrs.push(`groupBy="${rp.groupBy}"`);
2399
+ if (rp.startNum !== void 0) rpAttrs.push(`startNum="${rp.startNum}"`);
2400
+ if (rp.endNum !== void 0) rpAttrs.push(`endNum="${rp.endNum}"`);
2401
+ if (rp.startDate) rpAttrs.push(`startDate="${escapeXml(rp.startDate)}"`);
2402
+ if (rp.endDate) rpAttrs.push(`endDate="${escapeXml(rp.endDate)}"`);
2403
+ if (rp.groupInterval !== void 0) rpAttrs.push(`groupInterval="${rp.groupInterval}"`);
2404
+ fgParts.push(`<rangePr${rpAttrs.length ? " " + rpAttrs.join(" ") : ""}/>`);
2405
+ }
2406
+ if (fg.discretePr && fg.discretePr.length > 0) {
2407
+ fgParts.push(`<discretePr count="${fg.discretePr.length}">`);
2408
+ for (const idx of fg.discretePr) fgParts.push(`<x v="${idx}"/>`);
2409
+ fgParts.push("</discretePr>");
2410
+ }
2411
+ if (fg.groupItems && fg.groupItems.length > 0) {
2412
+ fgParts.push(`<groupItems count="${fg.groupItems.length}">`);
2413
+ for (const gi of fg.groupItems) fgParts.push(`<s v="${escapeXml(gi)}"/>`);
2414
+ fgParts.push("</groupItems>");
2415
+ }
2416
+ fgParts.push("</fieldGroup>");
2417
+ p.push(fgParts.join(""));
2418
+ }
2419
+ p.push("</cacheField>");
2420
+ }
2421
+ }
2422
+ p.push("</cacheFields>");
2423
+ if (this.cacheDefOpts?.mpMaps) for (const mp of this.cacheDefOpts.mpMaps) p.push(`<mpMap x="${mp.x}"/>`);
2424
+ if (this.olapPr) {
2425
+ const olAttrs = [];
2426
+ if (this.olapPr.local) olAttrs.push(` local="${escapeXml(this.olapPr.local)}"`);
2427
+ if (this.olapPr.localConnection) olAttrs.push(` localConnection="${escapeXml(this.olapPr.localConnection)}"`);
2428
+ if (this.olapPr.sendLocale) olAttrs.push(` sendLocale="1"`);
2429
+ if (this.olapPr.rowDrillCount !== void 0) olAttrs.push(` rowDrillCount="${this.olapPr.rowDrillCount}"`);
2430
+ if (this.olapPr.colDrillCount !== void 0) olAttrs.push(` colDrillCount="${this.olapPr.colDrillCount}"`);
2431
+ if (this.olapPr.localRefresh) olAttrs.push(" localRefresh=\"1\"");
2432
+ if (this.olapPr.serverFill === false) olAttrs.push(" serverFill=\"0\"");
2433
+ if (this.olapPr.serverNumberFormat === false) olAttrs.push(" serverNumberFormat=\"0\"");
2434
+ if (this.olapPr.serverFont === false) olAttrs.push(" serverFont=\"0\"");
2435
+ if (this.olapPr.serverFontColor === false) olAttrs.push(" serverFontColor=\"0\"");
2436
+ if (olAttrs.length > 0) p.push(`<olapPr${olAttrs.join("")}/>`);
2437
+ }
2438
+ if (this.cacheDefOpts?.cacheHierarchies && this.cacheDefOpts.cacheHierarchies.length > 0) {
2439
+ const chs = this.cacheDefOpts.cacheHierarchies;
2440
+ p.push(`<cacheHierarchies count="${chs.length}">`);
2441
+ for (const ch of chs) {
2442
+ const chAttrs = [`uniqueName="${escapeXml(ch.uniqueName)}"`, `count="${ch.count}"`];
2443
+ if (ch.caption) chAttrs.push(`caption="${escapeXml(ch.caption)}"`);
2444
+ if (ch.measure) chAttrs.push("measure=\"1\"");
2445
+ if (ch.set) chAttrs.push("set=\"1\"");
2446
+ if (ch.parentSet !== void 0) chAttrs.push(`parentSet="${ch.parentSet}"`);
2447
+ if (ch.iconSet !== void 0 && ch.iconSet !== 0) chAttrs.push(`iconSet="${ch.iconSet}"`);
2448
+ if (ch.attribute) chAttrs.push("attribute=\"1\"");
2449
+ if (ch.time) chAttrs.push("time=\"1\"");
2450
+ if (ch.keyAttribute) chAttrs.push("keyAttribute=\"1\"");
2451
+ if (ch.defaultMemberUniqueName) chAttrs.push(`defaultMemberUniqueName="${escapeXml(ch.defaultMemberUniqueName)}"`);
2452
+ if (ch.allUniqueName) chAttrs.push(`allUniqueName="${escapeXml(ch.allUniqueName)}"`);
2453
+ if (ch.allCaption) chAttrs.push(`allCaption="${escapeXml(ch.allCaption)}"`);
2454
+ if (ch.dimensionUniqueName) chAttrs.push(`dimensionUniqueName="${escapeXml(ch.dimensionUniqueName)}"`);
2455
+ if (ch.displayFolder) chAttrs.push(`displayFolder="${escapeXml(ch.displayFolder)}"`);
2456
+ if (ch.measureGroup) chAttrs.push(`measureGroup="${escapeXml(ch.measureGroup)}"`);
2457
+ if (ch.measures) chAttrs.push("measures=\"1\"");
2458
+ if (ch.oneField) chAttrs.push("oneField=\"1\"");
2459
+ if (ch.hidden) chAttrs.push("hidden=\"1\"");
2460
+ if (ch.memberValueDatatype) chAttrs.push(`memberValueDatatype="${ch.memberValueDatatype}"`);
2461
+ if (ch.unbalanced) chAttrs.push("unbalanced=\"1\"");
2462
+ if (ch.unbalancedGroup) chAttrs.push("unbalancedGroup=\"1\"");
2463
+ const hasGroupLevels = ch.groupLevels && ch.groupLevels.length > 0;
2464
+ const hasFieldsUsage = ch.fieldsUsage && ch.fieldsUsage.length > 0;
2465
+ if (hasGroupLevels || hasFieldsUsage) {
2466
+ p.push(`<cacheHierarchy ${chAttrs.join(" ")}>`);
2467
+ if (hasFieldsUsage) {
2468
+ const fuParts = [`<fieldsUsage count="${ch.fieldsUsage.length}">`];
2469
+ for (const fu of ch.fieldsUsage) fuParts.push(`<fieldUsage v="${fu.value}"/>`);
2470
+ fuParts.push("</fieldsUsage>");
2471
+ p.push(fuParts.join(""));
2472
+ }
2473
+ if (hasGroupLevels) {
2474
+ const glParts = [`<groupLevels count="${ch.groupLevels.length}">`];
2475
+ for (const gl of ch.groupLevels) {
2476
+ const glAttrs = [`uniqueName="${escapeXml(gl.uniqueName)}"`, `caption="${escapeXml(gl.caption)}"`];
2477
+ if (gl.user) glAttrs.push("user=\"1\"");
2478
+ if (gl.customRollUp) glAttrs.push("customRollUp=\"1\"");
2479
+ if (gl.groups && gl.groups.length > 0) {
2480
+ glParts.push(`<groupLevel ${glAttrs.join(" ")}><groups count="${gl.groups.length}">`);
2481
+ for (const lg of gl.groups) {
2482
+ const lgAttrs = [
2483
+ `name="${escapeXml(lg.name)}"`,
2484
+ `uniqueName="${escapeXml(lg.uniqueName)}"`,
2485
+ `caption="${escapeXml(lg.caption)}"`
2486
+ ];
2487
+ if (lg.uniqueParent) lgAttrs.push(`uniqueParent="${escapeXml(lg.uniqueParent)}"`);
2488
+ if (lg.id !== void 0) lgAttrs.push(`id="${lg.id}"`);
2489
+ glParts.push(`<group ${lgAttrs.join(" ")}><groupMembers count="${lg.members.length}">`);
2490
+ for (const gm of lg.members) {
2491
+ const gmAttrs = [`uniqueName="${escapeXml(gm.uniqueName)}"`];
2492
+ if (gm.group) gmAttrs.push("group=\"1\"");
2493
+ glParts.push(`<groupMember ${gmAttrs.join(" ")}/>`);
2494
+ }
2495
+ glParts.push("</groupMembers></group>");
2496
+ }
2497
+ glParts.push("</groups></groupLevel>");
2498
+ } else glParts.push(`<groupLevel ${glAttrs.join(" ")}/>`);
2499
+ }
2500
+ glParts.push("</groupLevels>");
2501
+ p.push(glParts.join(""));
2502
+ }
2503
+ p.push("</cacheHierarchy>");
2504
+ } else p.push(`<cacheHierarchy ${chAttrs.join(" ")}/>`);
2505
+ }
2506
+ p.push("</cacheHierarchies>");
2507
+ }
2508
+ if (this.cacheDefOpts?.kpis && this.cacheDefOpts.kpis.length > 0) {
2509
+ const kpis = this.cacheDefOpts.kpis;
2510
+ p.push(`<kpis count="${kpis.length}">`);
2511
+ for (const k of kpis) {
2512
+ const kAttrs = [`uniqueName="${escapeXml(k.uniqueName)}"`, `value="${escapeXml(k.value)}"`];
2513
+ if (k.caption) kAttrs.push(`caption="${escapeXml(k.caption)}"`);
2514
+ if (k.displayFolder) kAttrs.push(`displayFolder="${escapeXml(k.displayFolder)}"`);
2515
+ if (k.measureGroup) kAttrs.push(`measureGroup="${escapeXml(k.measureGroup)}"`);
2516
+ if (k.parent) kAttrs.push(`parent="${escapeXml(k.parent)}"`);
2517
+ if (k.goal) kAttrs.push(`goal="${escapeXml(k.goal)}"`);
2518
+ if (k.status) kAttrs.push(`status="${escapeXml(k.status)}"`);
2519
+ if (k.trend) kAttrs.push(`trend="${escapeXml(k.trend)}"`);
2520
+ if (k.weight) kAttrs.push(`weight="${escapeXml(k.weight)}"`);
2521
+ if (k.time) kAttrs.push(`time="${escapeXml(k.time)}"`);
2522
+ p.push(`<kpi ${kAttrs.join(" ")}/>`);
2523
+ }
2524
+ p.push("</kpis>");
2525
+ }
2526
+ if (this.cacheDefOpts?.measureGroups && this.cacheDefOpts.measureGroups.length > 0) {
2527
+ const mgs = this.cacheDefOpts.measureGroups;
2528
+ p.push(`<measureGroups count="${mgs.length}">`);
2529
+ for (const mg of mgs) p.push(`<measureGroup name="${escapeXml(mg.name)}" caption="${escapeXml(mg.caption)}"/>`);
2530
+ p.push("</measureGroups>");
2531
+ }
2532
+ if (this.cacheDefOpts?.measureDimensionMaps && this.cacheDefOpts.measureDimensionMaps.length > 0) {
2533
+ const mdm = this.cacheDefOpts.measureDimensionMaps;
2534
+ p.push(`<maps count="${mdm.length}">`);
2535
+ for (const m of mdm) {
2536
+ const mAttrs = [];
2537
+ if (m.measureGroup !== void 0) mAttrs.push(`measureGroup="${m.measureGroup}"`);
2538
+ if (m.dimension !== void 0) mAttrs.push(`dimension="${m.dimension}"`);
2539
+ p.push(`<map ${mAttrs.join(" ")}/>`);
2540
+ }
2541
+ p.push("</maps>");
2542
+ }
2543
+ if (this.cacheDefOpts?.dimensions && this.cacheDefOpts.dimensions.length > 0) {
2544
+ const dims = this.cacheDefOpts.dimensions;
2545
+ p.push(`<dimensions count="${dims.length}">`);
2546
+ for (const d of dims) {
2547
+ const dAttrs = [
2548
+ `name="${escapeXml(d.name)}"`,
2549
+ `uniqueName="${escapeXml(d.uniqueName)}"`,
2550
+ `caption="${escapeXml(d.caption)}"`
2551
+ ];
2552
+ if (d.measure) dAttrs.push("measure=\"1\"");
2553
+ p.push(`<dimension ${dAttrs.join(" ")}/>`);
2554
+ }
2555
+ p.push("</dimensions>");
2556
+ }
2557
+ const cd = this.cacheDefOpts;
2558
+ const hasEntries = cd?.entries && cd.entries.length > 0;
2559
+ const hasSets = cd?.sets && cd.sets.length > 0;
2560
+ const hasServerFormats = cd?.serverFormats && cd.serverFormats.length > 0;
2561
+ const hasQueryCache = cd?.queryCache && cd.queryCache.length > 0;
2562
+ if (hasEntries || hasSets || hasServerFormats || hasQueryCache) {
2563
+ p.push("<tupleCache>");
2564
+ if (hasEntries) {
2565
+ const entParts = [`<entries count="${cd.entries.length}">`];
2566
+ for (const ent of cd.entries) if (ent.type === "m") entParts.push("<m/>");
2567
+ else if (ent.type === "e" && ent.value !== void 0) entParts.push(`<e v="${ent.value}"/>`);
2568
+ else if (ent.value !== void 0) entParts.push(`<${ent.type} v="${ent.value}"/>`);
2569
+ entParts.push("</entries>");
2570
+ p.push(entParts.join(""));
2571
+ }
2572
+ if (hasSets) {
2573
+ p.push(`<sets count="${cd.sets.length}">`);
2574
+ for (const s of cd.sets) {
2575
+ const sAttrs = [`maxRank="${s.maxRank}"`, `setDefinition="${escapeXml(s.setDefinition)}"`];
2576
+ if (s.count !== void 0) sAttrs.push(`count="${s.count}"`);
2577
+ if (s.sortType && s.sortType !== "none") sAttrs.push(`sortType="${s.sortType}"`);
2578
+ if (s.queryFailed) sAttrs.push("queryFailed=\"1\"");
2579
+ p.push(`<set ${sAttrs.join(" ")}/>`);
2580
+ }
2581
+ p.push("</sets>");
2582
+ }
2583
+ if (hasServerFormats) {
2584
+ p.push(`<serverFormats count="${cd.serverFormats.length}">`);
2585
+ for (const sf of cd.serverFormats) {
2586
+ const sfAttrs = [];
2587
+ if (sf.culture) sfAttrs.push(`culture="${escapeXml(sf.culture)}"`);
2588
+ if (sf.format) sfAttrs.push(`format="${escapeXml(sf.format)}"`);
2589
+ p.push(`<serverFormat ${sfAttrs.join(" ")}/>`);
2590
+ }
2591
+ p.push("</serverFormats>");
2592
+ }
2593
+ if (hasQueryCache) {
2594
+ const qc = cd.queryCache;
2595
+ p.push(`<queryCache count="${qc.length}">`);
2596
+ for (const q of qc) {
2597
+ let qInner = "";
2598
+ if (q.tpls && q.tpls.length > 0) {
2599
+ qInner = `<tpls count="${q.tpls.length}">`;
2600
+ for (const tpl of q.tpls) if (tpl.items && tpl.items.length > 0) qInner += `<tpl>${tpl.items.map((i) => `<x v="${i}"/>`).join("")}</tpl>`;
2601
+ else qInner += "<tpl/>";
2602
+ qInner += "</tpls>";
2603
+ }
2604
+ if (qInner) p.push(`<query mdx="${escapeXml(q.mdx)}">${qInner}</query>`);
2605
+ else p.push(`<query mdx="${escapeXml(q.mdx)}"/>`);
2606
+ }
2607
+ p.push("</queryCache>");
2608
+ }
2609
+ p.push("</tupleCache>");
2610
+ }
2611
+ p.push("</pivotCacheDefinition>");
2612
+ return p.join("");
1239
2613
  }
1240
2614
  };
1241
2615
  //#endregion
@@ -1272,7 +2646,9 @@ var PivotCacheRecordsXml = class extends BaseXmlComponent {
1272
2646
  p.push("<r>");
1273
2647
  for (let i = 0; i < row.length; i++) {
1274
2648
  const val = row[i];
1275
- if (this.numericFields[i]) p.push(`<n v="${val}"/>`);
2649
+ if (val === null) p.push("<m/>");
2650
+ else if (val instanceof Date) p.push(`<d v="${val.toISOString().replace(/\.\d{3}Z$/, "Z")}"/>`);
2651
+ else if (this.numericFields[i]) p.push(`<n v="${val}"/>`);
1276
2652
  else {
1277
2653
  const idx = this.fieldIndexMaps[i].get(String(val)) ?? 0;
1278
2654
  p.push(`<x v="${idx}"/>`);
@@ -1316,7 +2692,9 @@ var PivotTableXml = class extends BaseXmlComponent {
1316
2692
  const rowFieldIndices = rowFieldNames.map((n) => fields.indexOf(n));
1317
2693
  const colFieldIndices = colFieldNames.map((n) => fields.indexOf(n));
1318
2694
  const dataFieldIndices = dataFields.map((df) => fields.indexOf(df.field));
1319
- const pivotFieldsXml = this.buildPivotFields(rowFieldIndices, colFieldIndices, dataFieldIndices);
2695
+ const pageFieldIndices = (o.pages ?? []).map((n) => fields.indexOf(n));
2696
+ const pivotFieldsXml = this.buildPivotFields(rowFieldIndices, colFieldIndices, dataFieldIndices, pageFieldIndices);
2697
+ const pageFieldsXml = this.buildPageFields(pageFieldIndices);
1320
2698
  const rowFieldsXml = this.buildRowFields(rowFieldIndices);
1321
2699
  const rowItemsXml = this.buildRowItems(rowFieldIndices);
1322
2700
  const colFieldsXml = this.buildColFields(colFieldIndices);
@@ -1324,44 +2702,222 @@ var PivotTableXml = class extends BaseXmlComponent {
1324
2702
  const dataFieldsXml = this.buildDataFields(dataFields, dataFieldIndices);
1325
2703
  const locationRef = this.computeLocationRef(location, rowFieldIndices, colFieldIndices, dataFields);
1326
2704
  const p = [];
1327
- p.push(`<pivotTableDefinition xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" name="${escapeXml(name)}" cacheId="${this.cacheId}" dataCaption="Values" updatedVersion="6" minRefreshableVersion="3" createdVersion="6" applyNumberFormats="0" applyBorderFormats="0" applyFontFormats="0" applyPatternFormats="0" applyAlignmentFormats="0" applyWidthHeightFormats="1" autoFormatId="0" useAutoFormatting="1" itemPrintTitles="1" indent="0" outline="1" outlineData="1" compact="1" compactData="1" rowGrandTotals="1" colGrandTotals="1">`);
1328
- p.push(`<location ref="${escapeXml(locationRef)}" firstHeaderRow="1" firstDataRow="${colFieldIndices.length + 1}" firstDataCol="${rowFieldIndices.length}"/>`);
2705
+ const defAttrs = [
2706
+ `name="${escapeXml(name)}"`,
2707
+ `cacheId="${this.cacheId}"`,
2708
+ "dataCaption=\"Values\"",
2709
+ "updatedVersion=\"6\"",
2710
+ "minRefreshableVersion=\"3\"",
2711
+ "createdVersion=\"6\"",
2712
+ "applyNumberFormats=\"0\"",
2713
+ "applyBorderFormats=\"0\"",
2714
+ "applyFontFormats=\"0\"",
2715
+ "applyPatternFormats=\"0\"",
2716
+ "applyAlignmentFormats=\"0\"",
2717
+ "applyWidthHeightFormats=\"1\"",
2718
+ "autoFormatId=\"0\"",
2719
+ "useAutoFormatting=\"1\"",
2720
+ "itemPrintTitles=\"1\"",
2721
+ "indent=\"0\"",
2722
+ "outline=\"1\"",
2723
+ "outlineData=\"1\"",
2724
+ "compact=\"1\"",
2725
+ "compactData=\"1\"",
2726
+ "rowGrandTotals=\"1\"",
2727
+ "colGrandTotals=\"1\""
2728
+ ];
2729
+ if (o.dataOnRows) defAttrs.push("dataOnRows=\"1\"");
2730
+ if (o.grandTotalCaption) defAttrs.push(`grandTotalCaption="${escapeXml(o.grandTotalCaption)}"`);
2731
+ if (o.errorCaption) defAttrs.push(`errorCaption="${escapeXml(o.errorCaption)}"`);
2732
+ if (o.showError) defAttrs.push("showError=\"1\"");
2733
+ if (o.missingCaption) defAttrs.push(`missingCaption="${escapeXml(o.missingCaption)}"`);
2734
+ if (o.showMissing === false) defAttrs.push("showMissing=\"0\"");
2735
+ if (o.pageStyle) defAttrs.push(`pageStyle="${escapeXml(o.pageStyle)}"`);
2736
+ if (o.pivotTableStyle) defAttrs.push(`pivotTableStyle="${escapeXml(o.pivotTableStyle)}"`);
2737
+ if (o.tag) defAttrs.push(`tag="${escapeXml(o.tag)}"`);
2738
+ if (o.showItems === false) defAttrs.push("showItems=\"0\"");
2739
+ if (o.editData) defAttrs.push("editData=\"1\"");
2740
+ if (o.disableFieldList) defAttrs.push("disableFieldList=\"1\"");
2741
+ if (o.showCalcMbrs === false) defAttrs.push("showCalcMbrs=\"0\"");
2742
+ if (o.visualTotals) defAttrs.push("visualTotals=\"1\"");
2743
+ if (o.showMultipleLabel === false) defAttrs.push("showMultipleLabel=\"0\"");
2744
+ if (o.showDataDropDown === false) defAttrs.push("showDataDropDown=\"0\"");
2745
+ if (o.showDrill === false) defAttrs.push("showDrill=\"0\"");
2746
+ if (o.printDrill) defAttrs.push("printDrill=\"1\"");
2747
+ if (o.showMemberPropertyTips) defAttrs.push("showMemberPropertyTips=\"1\"");
2748
+ if (o.showDataTips === false) defAttrs.push("showDataTips=\"0\"");
2749
+ if (o.enableWizard === false) defAttrs.push("enableWizard=\"0\"");
2750
+ if (o.enableDrill === false) defAttrs.push("enableDrill=\"0\"");
2751
+ if (o.enableFieldProperties === false) defAttrs.push("enableFieldProperties=\"0\"");
2752
+ if (o.pageWrap !== void 0) defAttrs.push(`pageWrap="${o.pageWrap}"`);
2753
+ if (o.pageOverThenDown) defAttrs.push("pageOverThenDown=\"1\"");
2754
+ if (o.subtotalHiddenItems) defAttrs.push("subtotalHiddenItems=\"1\"");
2755
+ if (o.fieldPrintTitles) defAttrs.push("fieldPrintTitles=\"1\"");
2756
+ if (o.mergeItem) defAttrs.push("mergeItem=\"1\"");
2757
+ if (o.showDropZones === false) defAttrs.push("showDropZones=\"0\"");
2758
+ if (o.showEmptyRow) defAttrs.push("showEmptyRow=\"1\"");
2759
+ if (o.showEmptyCol) defAttrs.push("showEmptyCol=\"1\"");
2760
+ if (o.showHeaders === false) defAttrs.push("showHeaders=\"0\"");
2761
+ if (o.published) defAttrs.push("published=\"1\"");
2762
+ if (o.gridDropZones === false) defAttrs.push("gridDropZones=\"0\"");
2763
+ if (o.multipleFieldFilters === false) defAttrs.push("multipleFieldFilters=\"0\"");
2764
+ if (o.rowHeaderCaption) defAttrs.push(`rowHeaderCaption="${escapeXml(o.rowHeaderCaption)}"`);
2765
+ if (o.colHeaderCaption) defAttrs.push(`colHeaderCaption="${escapeXml(o.colHeaderCaption)}"`);
2766
+ if (o.fieldListSortAscending) defAttrs.push("fieldListSortAscending=\"1\"");
2767
+ if (o.mdxSubqueries) defAttrs.push("mdxSubqueries=\"1\"");
2768
+ if (o.customListSort === false) defAttrs.push("customListSort=\"0\"");
2769
+ if (o.asteriskTotals) defAttrs.push("asteriskTotals=\"1\"");
2770
+ if (o.dataPosition !== void 0) defAttrs.push(`dataPosition="${o.dataPosition}"`);
2771
+ if (o.immersive) defAttrs.push("immersive=\"1\"");
2772
+ if (o.vacatedStyle) defAttrs.push(`vacatedStyle="${escapeXml(o.vacatedStyle)}"`);
2773
+ p.push(`<pivotTableDefinition xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ${defAttrs.join(" ")}>`);
2774
+ const locAttrs = [
2775
+ `ref="${escapeXml(locationRef)}"`,
2776
+ `firstHeaderRow="1"`,
2777
+ `firstDataRow="${colFieldIndices.length + 1}"`,
2778
+ `firstDataCol="${rowFieldIndices.length}"`
2779
+ ];
2780
+ if (o.locationColPageCount !== void 0) locAttrs.push(`colPageCount="${o.locationColPageCount}"`);
2781
+ if (o.locationRowPageCount !== void 0) locAttrs.push(`rowPageCount="${o.locationRowPageCount}"`);
2782
+ p.push(`<location ${locAttrs.join(" ")}/>`);
1329
2783
  p.push(pivotFieldsXml);
2784
+ if (o.pivotHierarchies && o.pivotHierarchies.length > 0) p.push(this.buildPivotHierarchies(o.pivotHierarchies));
2785
+ if (pageFieldIndices.length > 0) p.push(pageFieldsXml);
1330
2786
  p.push(rowFieldsXml);
1331
2787
  p.push(rowItemsXml);
1332
2788
  if (colFieldIndices.length > 0) p.push(colFieldsXml);
1333
2789
  p.push(colItemsXml);
1334
2790
  if (dataFields.length > 0) p.push(dataFieldsXml);
1335
2791
  p.push(`<pivotTableStyleInfo name="${escapeXml(style)}" showRowHeaders="1" showColHeaders="1" showRowStripes="0" showColStripes="0" showLastColumn="1"/>`);
2792
+ if (o.filters && o.filters.length > 0) p.push(this.buildFilters(o.filters));
2793
+ if (o.calculatedItems && o.calculatedItems.length > 0) p.push(this.buildCalculatedItems(o.calculatedItems));
2794
+ if (o.calculatedMembers && o.calculatedMembers.length > 0) p.push(this.buildCalculatedMembers(o.calculatedMembers));
2795
+ if (o.formats && o.formats.length > 0) {
2796
+ const fmtParts = [`<formats count="${o.formats.length}">`];
2797
+ for (const fmt of o.formats) {
2798
+ const fmtAttrs = [];
2799
+ if (fmt.action && fmt.action !== "formatting") fmtAttrs.push(`action="${fmt.action}"`);
2800
+ if (fmt.dxfId !== void 0) fmtAttrs.push(`dxfId="${fmt.dxfId}"`);
2801
+ fmtParts.push(`<format${fmtAttrs.length ? " " + fmtAttrs.join(" ") : ""}>${this.buildPivotAreaXml(fmt.pivotArea)}</format>`);
2802
+ }
2803
+ fmtParts.push("</formats>");
2804
+ p.push(fmtParts.join(""));
2805
+ }
2806
+ if (o.pivotConditionalFormats && o.pivotConditionalFormats.length > 0) p.push(this.buildPivotConditionalFormats(o.pivotConditionalFormats));
2807
+ if (o.chartFormats && o.chartFormats.length > 0) p.push(this.buildChartFormats(o.chartFormats));
2808
+ if (o.rowHierarchiesUsage && o.rowHierarchiesUsage.length > 0) {
2809
+ const rhu = o.rowHierarchiesUsage;
2810
+ p.push(`<rowHierarchiesUsage count="${rhu.length}">${rhu.map((h) => `<rowHierarchyUsage hierarchyUsage="${h.hierarchyUsage}"/>`).join("")}</rowHierarchiesUsage>`);
2811
+ }
2812
+ if (o.colHierarchiesUsage && o.colHierarchiesUsage.length > 0) {
2813
+ const chu = o.colHierarchiesUsage;
2814
+ p.push(`<colHierarchiesUsage count="${chu.length}">${chu.map((h) => `<colHierarchyUsage hierarchyUsage="${h.hierarchyUsage}"/>`).join("")}</colHierarchiesUsage>`);
2815
+ }
1336
2816
  p.push("</pivotTableDefinition>");
1337
2817
  return p.join("");
1338
2818
  }
1339
- buildPivotFields(rowIndices, colIndices, dataIndices) {
2819
+ buildFieldOverrideAttrs(fo) {
2820
+ const a = [];
2821
+ if (fo.allDrilled) a.push("allDrilled=\"1\"");
2822
+ if (fo.autoShow) a.push("autoShow=\"1\"");
2823
+ if (fo.countSubtotal) a.push("countSubtotal=\"1\"");
2824
+ if (fo.dataSourceSort) a.push("dataSourceSort=\"1\"");
2825
+ if (fo.defaultAttributeDrillState) a.push("defaultAttributeDrillState=\"1\"");
2826
+ if (fo.hiddenLevel) a.push("hiddenLevel=\"1\"");
2827
+ if (fo.hideNewItems) a.push("hideNewItems=\"1\"");
2828
+ if (fo.insertBlankRow) a.push("insertBlankRow=\"1\"");
2829
+ if (fo.insertPageBreak) a.push("insertPageBreak=\"1\"");
2830
+ if (fo.itemPageCount) a.push("itemPageCount=\"1\"");
2831
+ if (fo.measureFilter) a.push("measureFilter=\"1\"");
2832
+ if (fo.nonAutoSortDefault) a.push("nonAutoSortDefault=\"1\"");
2833
+ if (fo.productSubtotal) a.push("productSubtotal=\"1\"");
2834
+ if (fo.rankBy !== void 0) a.push(`rankBy="${fo.rankBy}"`);
2835
+ if (fo.serverField) a.push("serverField=\"1\"");
2836
+ if (fo.showDropDowns) a.push("showDropDowns=\"1\"");
2837
+ if (fo.showPropAsCaption) a.push("showPropAsCaption=\"1\"");
2838
+ if (fo.showPropCell) a.push("showPropCell=\"1\"");
2839
+ if (fo.showPropTip) a.push("showPropTip=\"1\"");
2840
+ if (fo.stdDevPSubtotal) a.push("stdDevPSubtotal=\"1\"");
2841
+ if (fo.stdDevSubtotal) a.push("stdDevSubtotal=\"1\"");
2842
+ if (fo.subtotalCaption) a.push(`subtotalCaption="${escapeXml(fo.subtotalCaption)}"`);
2843
+ if (fo.topAutoShow) a.push("topAutoShow=\"1\"");
2844
+ if (fo.uniqueMemberProperty) a.push("uniqueMemberProperty=\"1\"");
2845
+ if (fo.varPSubtotal) a.push("varPSubtotal=\"1\"");
2846
+ if (fo.varSubtotal) a.push("varSubtotal=\"1\"");
2847
+ return a.join(" ");
2848
+ }
2849
+ buildPivotFields(rowIndices, colIndices, dataIndices, pageIndices) {
1340
2850
  const fields = this.sourceData.fieldNames;
2851
+ const o = this.options;
1341
2852
  const parts = [`<pivotFields count="${fields.length}">`];
1342
2853
  for (let i = 0; i < fields.length; i++) {
1343
2854
  const isRow = rowIndices.includes(i);
1344
2855
  const isCol = colIndices.includes(i);
1345
- if (dataIndices.includes(i)) parts.push(`<pivotField dataField="1" showAll="0"/>`);
1346
- else if (isRow) {
2856
+ const isData = dataIndices.includes(i);
2857
+ const isPage = pageIndices.includes(i);
2858
+ const override = o.fieldOverrides?.find((fo) => fo.field === fields[i]);
2859
+ const extraAttrs = override ? this.buildFieldOverrideAttrs(override) : "";
2860
+ if (isData) {
2861
+ const dataFieldIdx = dataIndices.indexOf(i);
2862
+ const df = o.data[dataFieldIdx];
2863
+ const dfAttrs = ["dataField=\"1\"", "showAll=\"0\""];
2864
+ if (extraAttrs) dfAttrs.push(extraAttrs);
2865
+ if (df?.showDataAs) dfAttrs.push(`showDataAs="${df.showDataAs}"`);
2866
+ if (df?.baseField !== void 0) dfAttrs.push(`baseField="${df.baseField}"`);
2867
+ if (df?.baseItem !== void 0) dfAttrs.push(`baseItem="${df.baseItem}"`);
2868
+ if (o.autoSortScope || df?.sortByTupleItems && df.sortByTupleItems.length > 0) {
2869
+ const scopeChildren = [];
2870
+ if (o.autoSortScope) scopeChildren.push(this.buildPivotAreaXml(o.autoSortScope));
2871
+ if (df?.sortByTupleItems && df.sortByTupleItems.length > 0) {
2872
+ const tplXml = df.sortByTupleItems.map((v) => `<tpl><x v="${v}"/></tpl>`).join("");
2873
+ scopeChildren.push(`<sortByTuple>${tplXml}</sortByTuple>`);
2874
+ }
2875
+ parts.push(`<pivotField ${dfAttrs.join(" ")}><autoSortScope>${scopeChildren.join("")}</autoSortScope></pivotField>`);
2876
+ } else parts.push(`<pivotField ${dfAttrs.join(" ")}/>`);
2877
+ } else if (isRow) {
1347
2878
  const uniqueVals = collectUniqueValues(this.sourceData.records, i);
1348
- parts.push(`<pivotField axis="axisRow" showAll="0">`);
2879
+ const rAttrs = extraAttrs ? ` axis="axisRow" showAll="0" ${extraAttrs}` : " axis=\"axisRow\" showAll=\"0\"";
2880
+ parts.push(`<pivotField${rAttrs}>`);
1349
2881
  parts.push(`<items count="${uniqueVals.length + 1}">`);
1350
2882
  for (let j = 0; j < uniqueVals.length; j++) parts.push(`<item x="${j}"/>`);
1351
- parts.push(`<item t="default"/>`);
2883
+ parts.push(`<item t="default"${override?.defaultItemSd === false ? " sd=\"0\"" : ""}/>`);
1352
2884
  parts.push("</items></pivotField>");
1353
2885
  } else if (isCol) {
1354
2886
  const uniqueVals = collectUniqueValues(this.sourceData.records, i);
1355
- parts.push(`<pivotField axis="axisCol" showAll="0">`);
2887
+ const cAttrs = extraAttrs ? ` axis="axisCol" showAll="0" ${extraAttrs}` : " axis=\"axisCol\" showAll=\"0\"";
2888
+ parts.push(`<pivotField${cAttrs}>`);
1356
2889
  parts.push(`<items count="${uniqueVals.length + 1}">`);
1357
2890
  for (let j = 0; j < uniqueVals.length; j++) parts.push(`<item x="${j}"/>`);
1358
- parts.push(`<item t="default"/>`);
2891
+ parts.push(`<item t="default"${override?.defaultItemSd === false ? " sd=\"0\"" : ""}/>`);
1359
2892
  parts.push("</items></pivotField>");
1360
- } else parts.push(`<pivotField showAll="0"/>`);
2893
+ } else if (isPage) {
2894
+ const uniqueVals = collectUniqueValues(this.sourceData.records, i);
2895
+ const pAttrs = extraAttrs ? ` axis="axisPage" showAll="0" ${extraAttrs}` : " axis=\"axisPage\" showAll=\"0\"";
2896
+ parts.push(`<pivotField${pAttrs}>`);
2897
+ parts.push(`<items count="${uniqueVals.length + 1}">`);
2898
+ for (let j = 0; j < uniqueVals.length; j++) parts.push(`<item x="${j}"/>`);
2899
+ parts.push(`<item t="default"${override?.defaultItemSd === false ? " sd=\"0\"" : ""}/>`);
2900
+ parts.push("</items></pivotField>");
2901
+ } else {
2902
+ const nAttrs = extraAttrs ? ` showAll="0" ${extraAttrs}` : " showAll=\"0\"";
2903
+ parts.push(`<pivotField${nAttrs}/>`);
2904
+ }
1361
2905
  }
1362
2906
  parts.push("</pivotFields>");
1363
2907
  return parts.join("");
1364
2908
  }
2909
+ buildPageFields(pageIndices) {
2910
+ if (pageIndices.length === 0) return "";
2911
+ const o = this.options;
2912
+ const parts = [`<pageFields count="${pageIndices.length}">`];
2913
+ for (let i = 0; i < pageIndices.length; i++) {
2914
+ const cap = o.pageCaptions?.[i];
2915
+ const capAttr = cap ? ` cap="${escapeXml(cap)}"` : "";
2916
+ parts.push(`<pageField fld="${pageIndices[i]}" hier="${i}"${capAttr}/>`);
2917
+ }
2918
+ parts.push("</pageFields>");
2919
+ return parts.join("");
2920
+ }
1365
2921
  buildRowFields(rowIndices) {
1366
2922
  if (rowIndices.length === 0) return "<rowFields count=\"0\"/>";
1367
2923
  const parts = [`<rowFields count="${rowIndices.length}">`];
@@ -1428,8 +2984,15 @@ var PivotTableXml = class extends BaseXmlComponent {
1428
2984
  for (let i = 0; i < dataFields.length; i++) {
1429
2985
  const df = dataFields[i];
1430
2986
  const subtotal = df.summarize ?? "sum";
1431
- const name = df.name ?? `${subtotal === "sum" ? "Sum" : subtotal} of ${df.field}`;
1432
- parts.push(`<dataField name="${escapeXml(name)}" fld="${dataFieldIndices[i]}" subtotal="${subtotal}"/>`);
2987
+ const dfAttrs = [
2988
+ `name="${escapeXml(df.name ?? `${subtotal === "sum" ? "Sum" : subtotal} of ${df.field}`)}"`,
2989
+ `fld="${dataFieldIndices[i]}"`,
2990
+ `subtotal="${subtotal}"`
2991
+ ];
2992
+ if (df.showDataAs) dfAttrs.push(`showDataAs="${df.showDataAs}"`);
2993
+ if (df.baseField !== void 0) dfAttrs.push(`baseField="${df.baseField}"`);
2994
+ if (df.baseItem !== void 0) dfAttrs.push(`baseItem="${df.baseItem}"`);
2995
+ parts.push(`<dataField ${dfAttrs.join(" ")}/>`);
1433
2996
  }
1434
2997
  parts.push("</dataFields>");
1435
2998
  return parts.join("");
@@ -1448,6 +3011,160 @@ var PivotTableXml = class extends BaseXmlComponent {
1448
3011
  colCount += 1;
1449
3012
  return `${startCol}${startRow}:${colIndexToLetter(letterToColIndex(startCol) + colCount - 1)}${startRow + rowCount - 1}`;
1450
3013
  }
3014
+ buildFilters(filters) {
3015
+ const parts = [`<filters count="${filters.length}">`];
3016
+ for (const f of filters) {
3017
+ const fAttrs = {
3018
+ fld: f.fld,
3019
+ type: f.type,
3020
+ id: f.id
3021
+ };
3022
+ if (f.mpFld !== void 0) fAttrs.mpFld = f.mpFld;
3023
+ if (f.evalOrder !== void 0) fAttrs.evalOrder = f.evalOrder;
3024
+ if (f.iMeasureHier !== void 0) fAttrs.iMeasureHier = f.iMeasureHier;
3025
+ if (f.iMeasureFld !== void 0) fAttrs.iMeasureFld = f.iMeasureFld;
3026
+ if (f.name !== void 0) fAttrs.name = f.name;
3027
+ if (f.description !== void 0) fAttrs.description = f.description;
3028
+ if (f.stringValue1 !== void 0) fAttrs.stringValue1 = f.stringValue1;
3029
+ if (f.stringValue2 !== void 0) fAttrs.stringValue2 = f.stringValue2;
3030
+ parts.push(`<filter${attrs(fAttrs)}><autoFilter/></filter>`);
3031
+ }
3032
+ parts.push("</filters>");
3033
+ return parts.join("");
3034
+ }
3035
+ buildPivotHierarchies(hierarchies) {
3036
+ const parts = [`<pivotHierarchies count="${hierarchies.length}">`];
3037
+ for (const h of hierarchies) {
3038
+ const hAttrs = [];
3039
+ if (h.outline) hAttrs.push("outline=\"1\"");
3040
+ if (h.multipleItemSelectionAllowed) hAttrs.push("multipleItemSelectionAllowed=\"1\"");
3041
+ if (h.subtotalTop) hAttrs.push("subtotalTop=\"1\"");
3042
+ if (h.showInFieldList === false) hAttrs.push("showInFieldList=\"0\"");
3043
+ if (h.dragToRow === false) hAttrs.push("dragToRow=\"0\"");
3044
+ if (h.dragToCol === false) hAttrs.push("dragToCol=\"0\"");
3045
+ if (h.dragToPage === false) hAttrs.push("dragToPage=\"0\"");
3046
+ if (h.dragToData) hAttrs.push("dragToData=\"1\"");
3047
+ if (h.dragOff === false) hAttrs.push("dragOff=\"0\"");
3048
+ if (h.includeNewItemsInFilter) hAttrs.push("includeNewItemsInFilter=\"1\"");
3049
+ if (h.caption) hAttrs.push(`caption="${escapeXml(h.caption)}"`);
3050
+ const inner = (h.memberProperties ? `<mps count="${h.memberProperties.length}">${h.memberProperties.map((mp) => {
3051
+ const mpAttrs = [`field="${mp.field}"`];
3052
+ if (mp.name !== void 0) mpAttrs.push(`name="${escapeXml(mp.name)}"`);
3053
+ if (mp.showCell) mpAttrs.push("showCell=\"1\"");
3054
+ if (mp.showTip) mpAttrs.push("showTip=\"1\"");
3055
+ if (mp.showAsCaption) mpAttrs.push("showAsCaption=\"1\"");
3056
+ if (mp.nameLen !== void 0) mpAttrs.push(`nameLen="${mp.nameLen}"`);
3057
+ if (mp.pPos !== void 0) mpAttrs.push(`pPos="${mp.pPos}"`);
3058
+ if (mp.pLen !== void 0) mpAttrs.push(`pLen="${mp.pLen}"`);
3059
+ return `<mp ${mpAttrs.join(" ")}/>`;
3060
+ }).join("")}</mps>` : "") + (h.members ? `<members count="${h.members.length}">${h.members.map((m) => {
3061
+ const levelAttr = m.level !== void 0 ? ` level="${m.level}"` : "";
3062
+ return `<member name="${escapeXml(m.name)}"${levelAttr}/>`;
3063
+ }).join("")}</members>` : "");
3064
+ if (inner) parts.push(`<pivotHierarchy ${hAttrs.join(" ")}>${inner}</pivotHierarchy>`);
3065
+ else parts.push(`<pivotHierarchy ${hAttrs.join(" ")}/>`);
3066
+ }
3067
+ parts.push("</pivotHierarchies>");
3068
+ return parts.join("");
3069
+ }
3070
+ buildCalculatedItems(items) {
3071
+ const parts = [`<calculatedItems count="${items.length}">`];
3072
+ for (const item of items) {
3073
+ const ciAttrs = [];
3074
+ if (item.field !== void 0) ciAttrs.push(`field="${item.field}"`);
3075
+ if (item.formula) ciAttrs.push(`formula="${escapeXml(item.formula)}"`);
3076
+ const inner = item.pivotArea ? this.buildPivotAreaXml(item.pivotArea) : "";
3077
+ if (inner) parts.push(`<calculatedItem ${ciAttrs.join(" ")}>${inner}</calculatedItem>`);
3078
+ else parts.push(`<calculatedItem ${ciAttrs.join(" ")}/>`);
3079
+ }
3080
+ parts.push("</calculatedItems>");
3081
+ return parts.join("");
3082
+ }
3083
+ buildCalculatedMembers(members) {
3084
+ const parts = [`<calculatedMembers count="${members.length}">`];
3085
+ for (const m of members) {
3086
+ const mAttrs = [`name="${escapeXml(m.name)}"`, `mdx="${escapeXml(m.mdx)}"`];
3087
+ if (m.memberName) mAttrs.push(`memberName="${escapeXml(m.memberName)}"`);
3088
+ if (m.hierarchy) mAttrs.push(`hierarchy="${escapeXml(m.hierarchy)}"`);
3089
+ if (m.parent) mAttrs.push(`parent="${escapeXml(m.parent)}"`);
3090
+ if (m.solveOrder !== void 0) mAttrs.push(`solveOrder="${m.solveOrder}"`);
3091
+ if (m.set) mAttrs.push("set=\"1\"");
3092
+ parts.push(`<calculatedMember ${mAttrs.join(" ")}/>`);
3093
+ }
3094
+ parts.push("</calculatedMembers>");
3095
+ return parts.join("");
3096
+ }
3097
+ buildPivotConditionalFormats(formats) {
3098
+ const parts = [`<conditionalFormats count="${formats.length}">`];
3099
+ for (const cf of formats) {
3100
+ const cfAttrs = [`priority="${cf.priority}"`];
3101
+ if (cf.scope && cf.scope !== "selection") cfAttrs.push(`scope="${cf.scope}"`);
3102
+ if (cf.type && cf.type !== "none") cfAttrs.push(`type="${cf.type}"`);
3103
+ const areasXml = cf.pivotAreas?.map((a) => this.buildPivotAreaXml(a)).join("") ?? "";
3104
+ const pivotAreasXml = areasXml ? `<pivotAreas>${areasXml}</pivotAreas>` : "";
3105
+ parts.push(`<conditionalFormat ${cfAttrs.join(" ")}>${pivotAreasXml}</conditionalFormat>`);
3106
+ }
3107
+ parts.push("</conditionalFormats>");
3108
+ return parts.join("");
3109
+ }
3110
+ buildChartFormats(formats) {
3111
+ const parts = [`<chartFormats count="${formats.length}">`];
3112
+ for (const cf of formats) {
3113
+ const cfAttrs = [`chart="${cf.chart}"`, `format="${cf.format}"`];
3114
+ if (cf.series) cfAttrs.push("series=\"1\"");
3115
+ const areaXml = cf.pivotArea ? this.buildPivotAreaXml(cf.pivotArea) : "";
3116
+ if (areaXml) parts.push(`<chartFormat ${cfAttrs.join(" ")}>${areaXml}</chartFormat>`);
3117
+ else parts.push(`<chartFormat ${cfAttrs.join(" ")}/>`);
3118
+ }
3119
+ parts.push("</chartFormats>");
3120
+ return parts.join("");
3121
+ }
3122
+ buildPivotAreaXml(area) {
3123
+ const aAttrs = [];
3124
+ if (area.field !== void 0) aAttrs.push(`field="${area.field}"`);
3125
+ if (area.type) aAttrs.push(`type="${area.type}"`);
3126
+ if (area.dataOnly === false) aAttrs.push("dataOnly=\"0\"");
3127
+ if (area.labelOnly) aAttrs.push("labelOnly=\"1\"");
3128
+ if (area.grandRow) aAttrs.push("grandRow=\"1\"");
3129
+ if (area.grandCol) aAttrs.push("grandCol=\"1\"");
3130
+ if (area.cacheIndex) aAttrs.push("cacheIndex=\"1\"");
3131
+ if (area.outline === false) aAttrs.push("outline=\"0\"");
3132
+ if (area.offset) aAttrs.push(`offset="${escapeXml(area.offset)}"`);
3133
+ if (area.collapsedLevelsAreSubtotals) aAttrs.push("collapsedLevelsAreSubtotals=\"1\"");
3134
+ if (area.axis) aAttrs.push(`axis="${area.axis}"`);
3135
+ if (area.fieldPosition !== void 0) aAttrs.push(`fieldPosition="${area.fieldPosition}"`);
3136
+ const refsXml = area.references ? this.buildPivotAreaReferences(area.references) : "";
3137
+ if (refsXml) return `<pivotArea ${aAttrs.join(" ")}>${refsXml}</pivotArea>`;
3138
+ return `<pivotArea ${aAttrs.join(" ")}/>`;
3139
+ }
3140
+ buildPivotAreaReferences(refs) {
3141
+ const parts = [`<references count="${refs.length}">`];
3142
+ for (const ref of refs) {
3143
+ const rAttrs = [];
3144
+ if (ref.field !== void 0) rAttrs.push(`field="${ref.field}"`);
3145
+ if (ref.count !== void 0) rAttrs.push(`count="${ref.count}"`);
3146
+ if (ref.selected === false) rAttrs.push("selected=\"0\"");
3147
+ if (ref.byPosition) rAttrs.push("byPosition=\"1\"");
3148
+ if (ref.relative) rAttrs.push("relative=\"1\"");
3149
+ if (ref.defaultSubtotal) rAttrs.push("defaultSubtotal=\"1\"");
3150
+ if (ref.sumSubtotal) rAttrs.push("sumSubtotal=\"1\"");
3151
+ if (ref.countASubtotal) rAttrs.push("countASubtotal=\"1\"");
3152
+ if (ref.avgSubtotal) rAttrs.push("avgSubtotal=\"1\"");
3153
+ if (ref.maxSubtotal) rAttrs.push("maxSubtotal=\"1\"");
3154
+ if (ref.minSubtotal) rAttrs.push("minSubtotal=\"1\"");
3155
+ if (ref.countSubtotal) rAttrs.push("countSubtotal=\"1\"");
3156
+ if (ref.productSubtotal) rAttrs.push("productSubtotal=\"1\"");
3157
+ if (ref.stdDevPSubtotal) rAttrs.push("stdDevPSubtotal=\"1\"");
3158
+ if (ref.stdDevSubtotal) rAttrs.push("stdDevSubtotal=\"1\"");
3159
+ if (ref.varPSubtotal) rAttrs.push("varPSubtotal=\"1\"");
3160
+ if (ref.varSubtotal) rAttrs.push("varSubtotal=\"1\"");
3161
+ const xXml = ref.x ? ref.x.map((v) => `<x v="${v}"/>`).join("") : "";
3162
+ if (xXml) parts.push(`<reference ${rAttrs.join(" ")}>${xXml}</reference>`);
3163
+ else parts.push(`<reference ${rAttrs.join(" ")}/>`);
3164
+ }
3165
+ parts.push("</references>");
3166
+ return parts.join("");
3167
+ }
1451
3168
  };
1452
3169
  function letterToColIndex(letters) {
1453
3170
  let col = 0;
@@ -1476,6 +3193,1272 @@ function cartesianOfCounts(counts) {
1476
3193
  return result;
1477
3194
  }
1478
3195
  //#endregion
3196
+ //#region src/file/table/table-xml.ts
3197
+ /**
3198
+ * Table XML generator — generates xl/tables/table{n}.xml.
3199
+ *
3200
+ * Implements CT_Table from sml.xsd (transitional schema).
3201
+ *
3202
+ * @module
3203
+ */
3204
+ const TotalsRowFunction = {
3205
+ NONE: "none",
3206
+ SUM: "sum",
3207
+ MIN: "min",
3208
+ MAX: "max",
3209
+ AVERAGE: "average",
3210
+ COUNT: "count",
3211
+ COUNT_NUMS: "countNums",
3212
+ STD_DEV: "stdDev",
3213
+ VAR: "var",
3214
+ CUSTOM: "custom"
3215
+ };
3216
+ const TableType = {
3217
+ WORKSHEET: "worksheet",
3218
+ XML: "xml",
3219
+ QUERY_TABLE: "queryTable"
3220
+ };
3221
+ /**
3222
+ * Table XML component — generates xl/tables/table{n}.xml.
3223
+ *
3224
+ * Follows the zero-allocation string concatenation pattern used by other
3225
+ * XLSX components.
3226
+ */
3227
+ var TableXml = class extends BaseXmlComponent {
3228
+ opts;
3229
+ constructor(options) {
3230
+ super("table");
3231
+ this.opts = options;
3232
+ }
3233
+ toXml(_context) {
3234
+ const o = this.opts;
3235
+ const p = [];
3236
+ const rootAttrs = {
3237
+ id: o.id,
3238
+ name: o.name ?? o.displayName,
3239
+ displayName: o.displayName,
3240
+ ref: o.ref
3241
+ };
3242
+ if (o.tableType && o.tableType !== "worksheet") rootAttrs.tableType = o.tableType;
3243
+ if (o.headerRowCount !== void 0 && o.headerRowCount !== 1) rootAttrs.headerRowCount = o.headerRowCount;
3244
+ if (o.totalsRowCount !== void 0 && o.totalsRowCount > 0) rootAttrs.totalsRowCount = o.totalsRowCount;
3245
+ if (o.totalsRowShown === false) rootAttrs.totalsRowShown = 0;
3246
+ if (o.insertRowShift) rootAttrs.insertRowShift = 1;
3247
+ if (o.published) rootAttrs.published = 1;
3248
+ if (o.headerRowDxfId !== void 0) rootAttrs.headerRowDxfId = o.headerRowDxfId;
3249
+ if (o.dataDxfId !== void 0) rootAttrs.dataDxfId = o.dataDxfId;
3250
+ if (o.totalsRowDxfId !== void 0) rootAttrs.totalsRowDxfId = o.totalsRowDxfId;
3251
+ if (o.headerRowBorderDxfId !== void 0) rootAttrs.headerRowBorderDxfId = o.headerRowBorderDxfId;
3252
+ if (o.tableBorderDxfId !== void 0) rootAttrs.tableBorderDxfId = o.tableBorderDxfId;
3253
+ if (o.totalsRowBorderDxfId !== void 0) rootAttrs.totalsRowBorderDxfId = o.totalsRowBorderDxfId;
3254
+ if (o.headerRowCellStyle) rootAttrs.headerRowCellStyle = o.headerRowCellStyle;
3255
+ if (o.dataCellStyle) rootAttrs.dataCellStyle = o.dataCellStyle;
3256
+ if (o.totalsRowCellStyle) rootAttrs.totalsRowCellStyle = o.totalsRowCellStyle;
3257
+ 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"${this.buildAttrs(rootAttrs)}>`);
3258
+ if (o.autoFilter !== void 0) p.push(`<autoFilter ref="${escapeXml(o.autoFilter)}"/>`);
3259
+ p.push(`<tableColumns count="${o.columns.length}">`);
3260
+ for (let i = 0; i < o.columns.length; i++) {
3261
+ const col = o.columns[i];
3262
+ const colAttrs = {
3263
+ id: i + 1,
3264
+ name: col.name
3265
+ };
3266
+ const inner = [];
3267
+ if (col.calculatedColumnFormula !== void 0) {
3268
+ const fAttrs = col.calculatedColumnFormulaArray ? " array=\"1\"" : "";
3269
+ inner.push(`<calculatedColumnFormula${fAttrs}>${escapeXml(col.calculatedColumnFormula)}</calculatedColumnFormula>`);
3270
+ }
3271
+ if (col.totalsRowFormula !== void 0) {
3272
+ const fAttrs = col.totalsRowFormulaArray ? " array=\"1\"" : "";
3273
+ inner.push(`<totalsRowFormula${fAttrs}>${escapeXml(col.totalsRowFormula)}</totalsRowFormula>`);
3274
+ }
3275
+ if (col.totalsRowFunction !== void 0 && col.totalsRowFunction !== TotalsRowFunction.NONE) colAttrs.totalsRowFunction = col.totalsRowFunction;
3276
+ if (col.totalsRowLabel !== void 0) colAttrs.totalsRowLabel = col.totalsRowLabel;
3277
+ if (col.uniqueName) colAttrs.uniqueName = col.uniqueName;
3278
+ if (col.queryTableFieldId !== void 0) colAttrs.queryTableFieldId = col.queryTableFieldId;
3279
+ if (col.headerRowDxfId !== void 0) colAttrs.headerRowDxfId = col.headerRowDxfId;
3280
+ if (col.dataDxfId !== void 0) colAttrs.dataDxfId = col.dataDxfId;
3281
+ if (col.totalsRowDxfId !== void 0) colAttrs.totalsRowDxfId = col.totalsRowDxfId;
3282
+ if (col.headerRowCellStyle) colAttrs.headerRowCellStyle = col.headerRowCellStyle;
3283
+ if (col.dataCellStyle) colAttrs.dataCellStyle = col.dataCellStyle;
3284
+ if (col.totalsRowCellStyle) colAttrs.totalsRowCellStyle = col.totalsRowCellStyle;
3285
+ if (inner.length > 0) p.push(`<tableColumn${this.buildAttrs(colAttrs)}>${inner.join("")}</tableColumn>`);
3286
+ else p.push(`<tableColumn${this.buildAttrs(colAttrs)}/>`);
3287
+ }
3288
+ p.push("</tableColumns>");
3289
+ if (o.style) {
3290
+ const s = o.style;
3291
+ const styleAttrs = {};
3292
+ if (s.name !== void 0) styleAttrs.name = s.name;
3293
+ if (s.showFirstColumn) styleAttrs.showFirstColumn = 1;
3294
+ if (s.showLastColumn) styleAttrs.showLastColumn = 1;
3295
+ if (s.showRowStripes !== false) styleAttrs.showRowStripes = 1;
3296
+ if (s.showColumnStripes) styleAttrs.showColumnStripes = 1;
3297
+ p.push(`<tableStyleInfo${this.buildAttrs(styleAttrs)}/>`);
3298
+ } else p.push("<tableStyleInfo name=\"TableStyleMedium9\" showFirstColumn=\"0\" showLastColumn=\"0\" showRowStripes=\"1\" showColumnStripes=\"0\"/>");
3299
+ p.push("</table>");
3300
+ return p.join("");
3301
+ }
3302
+ buildAttrs(attrs) {
3303
+ const parts = [];
3304
+ for (const [k, v] of Object.entries(attrs)) {
3305
+ if (v === void 0) continue;
3306
+ parts.push(` ${k}="${typeof v === "string" ? escapeXml(v) : String(v)}"`);
3307
+ }
3308
+ return parts.join("");
3309
+ }
3310
+ };
3311
+ //#endregion
3312
+ //#region src/file/dialogsheet/dialogsheet.ts
3313
+ /**
3314
+ * Dialogsheet XML generator — produces xl/dialogsheets/sheetN.xml.
3315
+ *
3316
+ * A dialogsheet is a legacy Excel 5.0 dialog sheet (no cell data).
3317
+ *
3318
+ * Reference: OOXML transitional, sml.xsd, CT_Dialogsheet
3319
+ *
3320
+ * @module
3321
+ */
3322
+ var Dialogsheet = class extends BaseXmlComponent {
3323
+ opts;
3324
+ constructor(options) {
3325
+ super("dialogsheet");
3326
+ this.opts = options;
3327
+ }
3328
+ toXml(_context) {
3329
+ const p = ["<dialogsheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"];
3330
+ if (this.opts.tabColor) p.push(`<sheetPr><tabColor${attrs({ rgb: this.opts.tabColor })}/></sheetPr>`);
3331
+ p.push("<sheetViews><sheetView workbookViewId=\"0\"/></sheetViews>");
3332
+ if (this.opts.sheetProtection) {
3333
+ const sp = this.opts.sheetProtection;
3334
+ const spAttrs = {};
3335
+ if (sp.content) spAttrs.sheet = "1";
3336
+ if (sp.objects) spAttrs.objects = "1";
3337
+ if (sp.scenarios) spAttrs.scenarios = "1";
3338
+ if (Object.keys(spAttrs).length > 0) p.push(`<sheetProtection${attrs(spAttrs)}/>`);
3339
+ }
3340
+ if (this.opts.pageMargins) {
3341
+ const pm = this.opts.pageMargins;
3342
+ p.push(`<pageMargins${attrs({
3343
+ left: pm.left ?? .7,
3344
+ right: pm.right ?? .7,
3345
+ top: pm.top ?? .75,
3346
+ bottom: pm.bottom ?? .75,
3347
+ header: pm.header ?? .3,
3348
+ footer: pm.footer ?? .3
3349
+ })}/>`);
3350
+ }
3351
+ if (this.opts.pageSetup) {
3352
+ const ps = this.opts.pageSetup;
3353
+ p.push(`<pageSetup${attrs({
3354
+ paperSize: ps.paperSize,
3355
+ orientation: ps.orientation,
3356
+ horizontalDpi: ps.horizontalDpi,
3357
+ verticalDpi: ps.verticalDpi,
3358
+ copies: ps.copies
3359
+ })}/>`);
3360
+ }
3361
+ p.push("</dialogsheet>");
3362
+ return p.join("");
3363
+ }
3364
+ };
3365
+ //#endregion
3366
+ //#region src/file/query-table/query-table-xml.ts
3367
+ /**
3368
+ * QueryTable XML generator — produces xl/queryTables/queryTable{n}.xml.
3369
+ *
3370
+ * A query table represents data retrieved from an external data source.
3371
+ *
3372
+ * Reference: OOXML transitional, sml.xsd, CT_QueryTable
3373
+ *
3374
+ * @module
3375
+ */
3376
+ /** Preserve sort/filter layout (CT_QueryTableRefresh @preserveSortFilterLayout) */
3377
+ var QueryTableXml = class extends BaseXmlComponent {
3378
+ opts;
3379
+ constructor(options) {
3380
+ super("queryTable");
3381
+ this.opts = options;
3382
+ }
3383
+ toXml(_context) {
3384
+ const o = this.opts;
3385
+ const a = {
3386
+ name: o.name ?? "QueryTable1",
3387
+ connectionId: o.connectionId,
3388
+ autoFormat: o.autoFormat ? 1 : void 0,
3389
+ preserveFormatting: o.preserveFormatting ? 1 : void 0,
3390
+ adjustColumnWidth: o.adjustColumnWidth !== false ? 1 : 0,
3391
+ refreshOnLoad: o.refreshOnLoad ? 1 : void 0,
3392
+ backgroundRefresh: o.backgroundRefresh ? 1 : void 0,
3393
+ rowNumbers: o.rowNumbers ? 1 : void 0,
3394
+ disableRefresh: o.disableRefresh ? 1 : void 0,
3395
+ firstBackgroundRefresh: o.firstBackgroundRefresh ? 1 : void 0,
3396
+ growShrinkType: o.growShrinkType ? 1 : void 0,
3397
+ fillFormulas: o.fillFormulas ? 1 : void 0,
3398
+ removeDataOnSave: o.removeDataOnSave ? 1 : void 0,
3399
+ disableEdit: o.disableEdit ? 1 : void 0,
3400
+ intermediate: o.intermediate ? 1 : void 0
3401
+ };
3402
+ const children = [];
3403
+ if (o.queryTableRefresh) children.push(buildQueryTableRefresh(o.queryTableRefresh));
3404
+ if (children.length > 0) return `<queryTable xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"${attrs(a)}>${children.join("")}</queryTable>`;
3405
+ return `<queryTable xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"${attrs(a)}/>`;
3406
+ }
3407
+ };
3408
+ function buildQueryTableRefresh(opts) {
3409
+ const a = {};
3410
+ if (opts.nextId !== void 0) a.nextId = opts.nextId;
3411
+ if (opts.minimumVersion !== void 0) a.minimumVersion = opts.minimumVersion;
3412
+ if (opts.preserveFormatting) a.preserveFormatting = 1;
3413
+ if (opts.adjustColumnWidth !== void 0) a.adjustColumnWidth = opts.adjustColumnWidth ? 1 : 0;
3414
+ if (opts.refreshOnLoad) a.refreshOnLoad = 1;
3415
+ if (opts.backgroundRefresh) a.backgroundRefresh = 1;
3416
+ if (opts.rowCount !== void 0) a.rowCount = opts.rowCount;
3417
+ if (opts.fieldIdWrapped) a.fieldIdWrapped = 1;
3418
+ if (opts.headersInLastRefresh) a.headersInLastRefresh = 1;
3419
+ if (opts.preserveSortFilterLayout) a.preserveSortFilterLayout = 1;
3420
+ if (opts.unboundColumnsLeft !== void 0) a.unboundColumnsLeft = opts.unboundColumnsLeft;
3421
+ if (opts.unboundColumnsRight !== void 0) a.unboundColumnsRight = opts.unboundColumnsRight;
3422
+ const children = [];
3423
+ if (opts.deletedFields && opts.deletedFields.length > 0) {
3424
+ const dfParts = opts.deletedFields.map((df) => `<deletedField name="${escapeXml(df.name)}"/>`);
3425
+ children.push(`<queryTableDeletedFields count="${opts.deletedFields.length}">${dfParts.join("")}</queryTableDeletedFields>`);
3426
+ }
3427
+ if (opts.queryTableFields && opts.queryTableFields.length > 0) {
3428
+ const fParts = [`<queryTableFields count="${opts.queryTableFields.length}">`];
3429
+ for (const f of opts.queryTableFields) {
3430
+ const fAttrs = { id: f.id };
3431
+ if (f.name !== void 0) fAttrs.name = f.name;
3432
+ if (f.tableColumnId !== void 0) fAttrs.tableColumnId = f.tableColumnId;
3433
+ if (f.row !== void 0) fAttrs.row = f.row;
3434
+ if (f.fillFormatting) fAttrs.fillFormatting = 1;
3435
+ if (f.textFormatting) fAttrs.textFormatting = 1;
3436
+ if (f.numberFormatting) fAttrs.numberFormatting = 1;
3437
+ if (f.borderFormatting) fAttrs.borderFormatting = 1;
3438
+ if (f.width !== void 0) fAttrs.width = f.width;
3439
+ if (f.clipped) fAttrs.clipped = 1;
3440
+ if (f.dataBound !== void 0) fAttrs.dataBound = f.dataBound ? 1 : 0;
3441
+ fParts.push(`<queryTableField${attrs(fAttrs)}/>`);
3442
+ }
3443
+ fParts.push("</queryTableFields>");
3444
+ children.push(fParts.join(""));
3445
+ }
3446
+ if (children.length > 0) return `<queryTableRefresh${attrs(a)}>${children.join("")}</queryTableRefresh>`;
3447
+ return `<queryTableRefresh${attrs(a)}/>`;
3448
+ }
3449
+ //#endregion
3450
+ //#region src/file/metadata/metadata-xml.ts
3451
+ /**
3452
+ * Metadata XML generator — produces xl/metadata.xml.
3453
+ *
3454
+ * Contains cell metadata and value metadata for rich data types.
3455
+ *
3456
+ * Reference: OOXML transitional, sml.xsd, CT_Metadata
3457
+ *
3458
+ * @module
3459
+ */
3460
+ var MetadataXml = class extends BaseXmlComponent {
3461
+ opts;
3462
+ constructor(options) {
3463
+ super("metadata");
3464
+ this.opts = options;
3465
+ }
3466
+ toXml(_context) {
3467
+ const p = ["<metadata xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">"];
3468
+ const types = this.opts.types ?? [];
3469
+ p.push(`<metadataTypes count="${types.length}">`);
3470
+ for (const t of types) p.push(`<metadataType${attrs({
3471
+ name: t.name,
3472
+ minVersion: t.minVersion,
3473
+ minSupportedVersion: t.minSupportedVersion,
3474
+ ghostRow: t.ghostRow ? 1 : void 0,
3475
+ ghostCol: t.ghostCol ? 1 : void 0,
3476
+ edit: t.edit ? 1 : void 0,
3477
+ delete: t.delete ? 1 : void 0,
3478
+ copy: t.copy ? 1 : void 0,
3479
+ paste: t.paste ? 1 : void 0,
3480
+ pasteAll: t.pasteAll ? 1 : void 0,
3481
+ pasteFormulas: t.pasteFormulas ? 1 : void 0,
3482
+ pasteValues: t.pasteValues ? 1 : void 0,
3483
+ pasteFormats: t.pasteFormats ? 1 : void 0,
3484
+ pasteComments: t.pasteComments ? 1 : void 0,
3485
+ pasteDataValidation: t.pasteDataValidation ? 1 : void 0,
3486
+ pasteBorders: t.pasteBorders ? 1 : void 0,
3487
+ pasteColWidths: t.pasteColWidths ? 1 : void 0,
3488
+ pasteNumberFormats: t.pasteNumberFormats ? 1 : void 0,
3489
+ merge: t.merge ? 1 : void 0,
3490
+ splitFirst: t.splitFirst ? 1 : void 0,
3491
+ splitAll: t.splitAll ? 1 : void 0,
3492
+ rowColShift: t.rowColShift ? 1 : void 0,
3493
+ clearAll: t.clearAll ? 1 : void 0,
3494
+ clearFormats: t.clearFormats ? 1 : void 0,
3495
+ clearContents: t.clearContents ? 1 : void 0,
3496
+ clearComments: t.clearComments ? 1 : void 0,
3497
+ assign: t.assign ? 1 : void 0,
3498
+ coerce: t.coerce ? 1 : void 0,
3499
+ adjust: t.adjust ? 1 : void 0,
3500
+ cellMeta: t.cellMeta ? 1 : void 0
3501
+ })}/>`);
3502
+ p.push("</metadataTypes>");
3503
+ const strings = this.opts.strings ?? [];
3504
+ if (strings.length > 0) {
3505
+ p.push(`<metadataStrings count="${strings.length}">`);
3506
+ for (const s of strings) p.push(`<s v="${s.value}"/>`);
3507
+ p.push("</metadataStrings>");
3508
+ }
3509
+ const future = this.opts.futureMetadata ?? [];
3510
+ if (future.length > 0) for (const f of future) {
3511
+ p.push(`<futureMetadata name="${f.name}" type="${f.type}"><bk/>`);
3512
+ p.push("</futureMetadata>");
3513
+ }
3514
+ const cmBlocks = this.opts.cellMetadataBlocks ?? [];
3515
+ if (cmBlocks.length > 0) {
3516
+ p.push(`<cellMetadata count="${cmBlocks.length}">`);
3517
+ for (const blk of cmBlocks) {
3518
+ const records = blk.records ?? [];
3519
+ if (records.length > 0) {
3520
+ const rcParts = records.map((r) => `<rc t="${r.t}" v="${r.v}"/>`);
3521
+ p.push(`<bk>${rcParts.join("")}</bk>`);
3522
+ } else p.push("<bk/>");
3523
+ }
3524
+ p.push("</cellMetadata>");
3525
+ } else p.push("<cellMetadata count=\"0\"/>");
3526
+ const vmBlocks = this.opts.valueMetadataBlocks ?? [];
3527
+ if (vmBlocks.length > 0) {
3528
+ p.push(`<valueMetadata count="${vmBlocks.length}">`);
3529
+ for (const blk of vmBlocks) {
3530
+ const records = blk.records ?? [];
3531
+ if (records.length > 0) {
3532
+ const rcParts = records.map((r) => `<rc t="${r.t}" v="${r.v}"/>`);
3533
+ p.push(`<bk>${rcParts.join("")}</bk>`);
3534
+ } else p.push("<bk/>");
3535
+ }
3536
+ p.push("</valueMetadata>");
3537
+ } else p.push("<valueMetadata count=\"0\"/>");
3538
+ const mdxMeta = this.opts.mdxMetadata;
3539
+ if (mdxMeta && mdxMeta.length > 0) {
3540
+ p.push(`<mdxMetadata count="${mdxMeta.length}">`);
3541
+ for (const m of mdxMeta) {
3542
+ const mAttrs = {
3543
+ n: m.n,
3544
+ f: m.f
3545
+ };
3546
+ let child = "";
3547
+ if (m.tuple) {
3548
+ const tAttrs = {};
3549
+ if (m.tuple.c !== void 0) tAttrs.c = m.tuple.c;
3550
+ child = `<t${attrs(tAttrs)}/>`;
3551
+ } else if (m.set) child = `<ms ns="${m.set.ns}"/>`;
3552
+ else if (m.memberProp) child = `<p n="${m.memberProp.n}" np="${m.memberProp.np}"/>`;
3553
+ else if (m.kpi) child = `<k n="${m.kpi.n}" np="${m.kpi.np}" p="${escapeXml(m.kpi.p)}"/>`;
3554
+ if (child) p.push(`<mdx${attrs(mAttrs)}>${child}</mdx>`);
3555
+ else p.push(`<mdx${attrs(mAttrs)}/>`);
3556
+ }
3557
+ p.push("</mdxMetadata>");
3558
+ }
3559
+ p.push("</metadata>");
3560
+ return p.join("");
3561
+ }
3562
+ };
3563
+ //#endregion
3564
+ //#region src/file/revision-log/revision-headers-xml.ts
3565
+ /**
3566
+ * Revision Headers XML generator — produces xl/revisionHeaders.xml.
3567
+ *
3568
+ * Reference: OOXML transitional, sml.xsd, CT_RevisionHeaders
3569
+ *
3570
+ * @module
3571
+ */
3572
+ var RevisionHeadersXml = class extends BaseXmlComponent {
3573
+ opts;
3574
+ users;
3575
+ constructor(options, users) {
3576
+ super("headers");
3577
+ this.opts = options;
3578
+ this.users = users;
3579
+ }
3580
+ toXml(_context) {
3581
+ const p = ["<headers xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\""];
3582
+ const rootAttrs = {
3583
+ guid: this.opts.guid,
3584
+ lastGuid: this.opts.lastGuid,
3585
+ shared: this.opts.shared,
3586
+ history: this.opts.history,
3587
+ trackRevisions: this.opts.trackRevisions,
3588
+ revisionId: this.opts.revisionId,
3589
+ version: this.opts.version,
3590
+ keepChangeHistory: this.opts.keepChangeHistory,
3591
+ protected: this.opts.protected,
3592
+ preserveHistory: this.opts.preserveHistory,
3593
+ diskRevisions: this.opts.diskRevisions,
3594
+ exclusive: this.opts.exclusive
3595
+ };
3596
+ p.push(`${attrs(rootAttrs)}>`);
3597
+ for (const h of this.opts.headers) {
3598
+ const headerAttrs = {
3599
+ guid: h.guid,
3600
+ dateTime: h.dateTime,
3601
+ maxSheetId: h.maxSheetId,
3602
+ userName: h.userName
3603
+ };
3604
+ const content = [];
3605
+ if (h.sheetIds && h.sheetIds.length > 0) {
3606
+ const idParts = [];
3607
+ for (const sid of h.sheetIds) idParts.push(`<sheetId val="${sid.id}"/>`);
3608
+ content.push(`<sheetIdMap${attrs({ count: h.sheetIds.length })}>${idParts.join("")}</sheetIdMap>`);
3609
+ }
3610
+ p.push(`<header${attrs(headerAttrs)} r:id="${escapeXml(h.rId)}">${content.join("")}</header>`);
3611
+ }
3612
+ p.push("</headers>");
3613
+ return p.join("");
3614
+ }
3615
+ /** Build users XML (CT_Users) — separate file xl/users.xml */
3616
+ buildUsersXml() {
3617
+ if (!this.users?.users || this.users.users.length === 0) return "";
3618
+ const u = this.users.users;
3619
+ const parts = ["<users xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"", ` count="${u.length}">`];
3620
+ for (const user of u) {
3621
+ const uAttrs = {
3622
+ guid: user.guid,
3623
+ name: user.name,
3624
+ id: user.id,
3625
+ dateTime: user.dateTime
3626
+ };
3627
+ parts.push(`<userInfo${attrs(uAttrs)}/>`);
3628
+ }
3629
+ parts.push("</users>");
3630
+ return parts.join("");
3631
+ }
3632
+ };
3633
+ //#endregion
3634
+ //#region src/file/revision-log/revision-xml.ts
3635
+ /**
3636
+ * Revision Log XML generator — produces xl/revisions/revisionN.xml.
3637
+ *
3638
+ * Reference: OOXML transitional, sml.xsd, CT_Revisions
3639
+ *
3640
+ * @module
3641
+ */
3642
+ function buildRowColumn(opts) {
3643
+ const a = {
3644
+ rId: opts.rId,
3645
+ action: {
3646
+ insertRow: "ir",
3647
+ insertCol: "ic",
3648
+ deleteRow: "dr",
3649
+ deleteCol: "dc"
3650
+ }[opts.action],
3651
+ sId: opts.sheetIndex,
3652
+ edge: opts.edge ? 1 : void 0,
3653
+ ra: opts.ra,
3654
+ ua: opts.ua,
3655
+ eol: opts.eol ? 1 : void 0
3656
+ };
3657
+ if (opts.action.includes("Row")) a.row = opts.row;
3658
+ else a.col = opts.col;
3659
+ return `<rrc${attrs(a)}/>`;
3660
+ }
3661
+ function buildCellChange(opts) {
3662
+ const a = {
3663
+ rId: opts.rId,
3664
+ sId: opts.sheetIndex,
3665
+ quotePrefix: opts.quotePrefix ? 1 : void 0,
3666
+ oldQuotePrefix: opts.oldQuotePrefix ? 1 : void 0,
3667
+ ph: opts.ph ? 1 : void 0,
3668
+ oldPh: opts.oldPh ? 1 : void 0,
3669
+ ra: opts.ra,
3670
+ ua: opts.ua
3671
+ };
3672
+ const children = [];
3673
+ if (opts.oldValue !== void 0) {
3674
+ const oldType = opts.oldType ?? (typeof opts.oldValue === "number" ? "n" : "s");
3675
+ if (opts.formula) children.push(`<f>${escapeXml(opts.formula)}</f>`);
3676
+ const ocAttrs = {
3677
+ t: oldType,
3678
+ vm: opts.numFmtId
3679
+ };
3680
+ if (opts.oldCellMeta !== void 0) ocAttrs.cm = opts.oldCellMeta;
3681
+ children.push(`<oc${attrs(ocAttrs)}><v>${escapeXml(String(opts.oldValue))}</v></oc>`);
3682
+ }
3683
+ if (opts.newValue !== void 0) {
3684
+ const ncAttrs = { t: opts.newType ?? (typeof opts.newValue === "number" ? "n" : "s") };
3685
+ if (opts.newCellMeta !== void 0) ncAttrs.cm = opts.newCellMeta;
3686
+ children.push(`<nc${attrs(ncAttrs)}><v>${escapeXml(String(opts.newValue))}</v></nc>`);
3687
+ }
3688
+ if (opts.xfDxf !== void 0) {
3689
+ children.push(`<ndxf><font/><numFmt/><fill/><border/><protection/></ndxf>`);
3690
+ children.push(`<odxf><font/><numFmt/><fill/><border/><protection/></odxf>`);
3691
+ }
3692
+ return `<rcc${attrs({
3693
+ ref: opts.ref,
3694
+ ...a
3695
+ })}>${children.join("")}</rcc>`;
3696
+ }
3697
+ function buildMove(opts) {
3698
+ return `<rm${attrs({
3699
+ rId: opts.rId,
3700
+ sId: opts.sheetIndex,
3701
+ source: opts.source,
3702
+ destination: opts.destination,
3703
+ sourceSheetId: opts.sourceSheetId,
3704
+ ra: opts.ra,
3705
+ ua: opts.ua
3706
+ })}/>`;
3707
+ }
3708
+ function buildFormatting(opts) {
3709
+ return `<rfmt${attrs({
3710
+ rId: opts.rId,
3711
+ sId: opts.sheetIndex,
3712
+ ref: opts.ref,
3713
+ s: opts.s,
3714
+ xfDxf: opts.xfDxf
3715
+ })}/>`;
3716
+ }
3717
+ function buildInsertSheet(opts) {
3718
+ return `<ris${attrs({
3719
+ rId: opts.rId,
3720
+ sId: opts.sheetIndex,
3721
+ name: opts.name,
3722
+ sheetPosition: opts.sheetPosition,
3723
+ ra: opts.ra,
3724
+ ua: opts.ua
3725
+ })}/>`;
3726
+ }
3727
+ function buildComment(opts) {
3728
+ const a = {
3729
+ rId: opts.rId,
3730
+ sId: opts.sheetIndex,
3731
+ ref: opts.ref,
3732
+ alwaysShow: opts.alwaysShow ? 1 : void 0,
3733
+ old: opts.old ? 1 : void 0,
3734
+ hiddenRow: opts.hiddenRow ? 1 : void 0,
3735
+ hiddenColumn: opts.hiddenColumn ? 1 : void 0,
3736
+ oldLength: opts.oldLength,
3737
+ newLength: opts.newLength
3738
+ };
3739
+ const children = [];
3740
+ if (opts.text) children.push(`<t>${escapeXml(opts.text)}</t>`);
3741
+ if (opts.author) children.push(`<author>${escapeXml(opts.author)}</author>`);
3742
+ if (children.length > 0) return `<rcmt${attrs(a)}>${children.join("")}</rcmt>`;
3743
+ return `<rcmt${attrs(a)}/>`;
3744
+ }
3745
+ function buildDefinedName(opts) {
3746
+ const a = {
3747
+ rId: opts.rId,
3748
+ name: opts.name,
3749
+ localSheetId: opts.localSheetId,
3750
+ customView: opts.customView ? 1 : void 0,
3751
+ function: opts["function"] ? 1 : void 0,
3752
+ oldFunction: opts.oldFunction ? 1 : void 0,
3753
+ functionGroupId: opts.functionGroupId,
3754
+ oldFunctionGroupId: opts.oldFunctionGroupId,
3755
+ shortcutKey: opts.shortcutKey,
3756
+ oldShortcutKey: opts.oldShortcutKey,
3757
+ oldHidden: opts.oldHidden ? 1 : void 0,
3758
+ customMenu: opts.customMenu,
3759
+ oldCustomMenu: opts.oldCustomMenu,
3760
+ oldDescription: opts.oldDescription,
3761
+ help: opts.help,
3762
+ oldHelp: opts.oldHelp,
3763
+ statusBar: opts.statusBar,
3764
+ oldStatusBar: opts.oldStatusBar,
3765
+ ra: opts.ra,
3766
+ ua: opts.ua
3767
+ };
3768
+ const children = [];
3769
+ if (opts.value) children.push(`<formula>${escapeXml(opts.value)}</formula>`);
3770
+ if (opts.oldComment) children.push(`<oldFormula>${escapeXml(opts.oldComment)}</oldFormula>`);
3771
+ return `<rdn${attrs(a)}>${children.join("")}</rdn>`;
3772
+ }
3773
+ function buildAutoFormatting(opts) {
3774
+ return `<raf${attrs({
3775
+ rId: opts.rId,
3776
+ sId: opts.sheetIndex,
3777
+ ref: opts.ref
3778
+ })}/>`;
3779
+ }
3780
+ function buildCustomView(opts) {
3781
+ return `<rcv${attrs({
3782
+ rId: opts.rId,
3783
+ guid: opts.guid
3784
+ })}/>`;
3785
+ }
3786
+ function buildSheetRename(opts) {
3787
+ return `<rsnm${attrs({
3788
+ rId: opts.rId,
3789
+ sId: opts.sheetIndex,
3790
+ oldName: opts.oldName,
3791
+ newName: opts.newName,
3792
+ ra: opts.ra,
3793
+ ua: opts.ua
3794
+ })}/>`;
3795
+ }
3796
+ function buildQueryTableField(opts) {
3797
+ return `<rqt${attrs({
3798
+ rId: opts.rId,
3799
+ sId: opts.sheetIndex,
3800
+ fieldId: opts.fieldId,
3801
+ ra: opts.ra,
3802
+ ua: opts.ua
3803
+ })}/>`;
3804
+ }
3805
+ function buildConflict(opts) {
3806
+ return `<rcft${attrs({
3807
+ rId: opts.rId,
3808
+ sId: opts.sheetIndex,
3809
+ ra: opts.ra,
3810
+ ua: opts.ua
3811
+ })}/>`;
3812
+ }
3813
+ var RevisionLogXml = class extends BaseXmlComponent {
3814
+ entries;
3815
+ constructor(entries) {
3816
+ super("revisions");
3817
+ this.entries = entries;
3818
+ }
3819
+ toXml(_context) {
3820
+ const p = ["<revisions xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"];
3821
+ const localReviewedList = [];
3822
+ for (const entry of this.entries) switch (entry.type) {
3823
+ case "rowColumn":
3824
+ p.push(buildRowColumn(entry.data));
3825
+ break;
3826
+ case "cellChange":
3827
+ p.push(buildCellChange(entry.data));
3828
+ break;
3829
+ case "move":
3830
+ p.push(buildMove(entry.data));
3831
+ break;
3832
+ case "formatting":
3833
+ p.push(buildFormatting(entry.data));
3834
+ break;
3835
+ case "insertSheet":
3836
+ p.push(buildInsertSheet(entry.data));
3837
+ break;
3838
+ case "comment":
3839
+ p.push(buildComment(entry.data));
3840
+ break;
3841
+ case "definedName":
3842
+ p.push(buildDefinedName(entry.data));
3843
+ break;
3844
+ case "reviewed":
3845
+ localReviewedList.push(`<reviewed rId="${entry.data.rId}"/>`);
3846
+ p.push(`<reviewed rId="${entry.data.rId}"/>`);
3847
+ break;
3848
+ case "undo": {
3849
+ const undoAttrs = {
3850
+ rId: entry.data.rId,
3851
+ cs: entry.data.cs ? 1 : void 0,
3852
+ dn: entry.data.dn ? 1 : void 0,
3853
+ exp: entry.data.exp ? 1 : void 0,
3854
+ nf: entry.data.nf ? 1 : void 0,
3855
+ ref3D: entry.data.ref3D ? 1 : void 0
3856
+ };
3857
+ if (entry.data.revisions && entry.data.revisions.length > 0) {
3858
+ const innerParts = [];
3859
+ for (const inner of entry.data.revisions) switch (inner.type) {
3860
+ case "rowColumn":
3861
+ innerParts.push(buildRowColumn(inner.data));
3862
+ break;
3863
+ case "cellChange":
3864
+ innerParts.push(buildCellChange(inner.data));
3865
+ break;
3866
+ case "move":
3867
+ innerParts.push(buildMove(inner.data));
3868
+ break;
3869
+ case "formatting":
3870
+ innerParts.push(buildFormatting(inner.data));
3871
+ break;
3872
+ case "insertSheet":
3873
+ innerParts.push(buildInsertSheet(inner.data));
3874
+ break;
3875
+ case "comment":
3876
+ innerParts.push(buildComment(inner.data));
3877
+ break;
3878
+ case "definedName":
3879
+ innerParts.push(buildDefinedName(inner.data));
3880
+ break;
3881
+ case "reviewed":
3882
+ innerParts.push(`<reviewed rId="${inner.data.rId}"/>`);
3883
+ break;
3884
+ case "autoFormatting":
3885
+ innerParts.push(buildAutoFormatting(inner.data));
3886
+ break;
3887
+ case "customView":
3888
+ innerParts.push(buildCustomView(inner.data));
3889
+ break;
3890
+ case "sheetRename":
3891
+ innerParts.push(buildSheetRename(inner.data));
3892
+ break;
3893
+ case "queryTableField":
3894
+ innerParts.push(buildQueryTableField(inner.data));
3895
+ break;
3896
+ case "conflict":
3897
+ innerParts.push(buildConflict(inner.data));
3898
+ break;
3899
+ }
3900
+ p.push(`<undo${attrs(undoAttrs)}>${innerParts.join("")}</undo>`);
3901
+ } else p.push(`<undo${attrs(undoAttrs)}/>`);
3902
+ break;
3903
+ }
3904
+ case "autoFormatting":
3905
+ p.push(buildAutoFormatting(entry.data));
3906
+ break;
3907
+ case "customView":
3908
+ p.push(buildCustomView(entry.data));
3909
+ break;
3910
+ case "sheetRename":
3911
+ p.push(buildSheetRename(entry.data));
3912
+ break;
3913
+ case "queryTableField":
3914
+ p.push(buildQueryTableField(entry.data));
3915
+ break;
3916
+ case "conflict":
3917
+ p.push(buildConflict(entry.data));
3918
+ break;
3919
+ }
3920
+ if (localReviewedList.length > 0) p.push(`<reviewedList>${localReviewedList.join("")}</reviewedList>`);
3921
+ p.push("</revisions>");
3922
+ return p.join("");
3923
+ }
3924
+ };
3925
+ //#endregion
3926
+ //#region src/file/connection/connection-xml.ts
3927
+ /**
3928
+ * Connection XML generator — produces xl/connections.xml.
3929
+ *
3930
+ * Reference: OOXML transitional, sml.xsd, CT_Connections
3931
+ *
3932
+ * @module
3933
+ */
3934
+ var ConnectionsXml = class extends BaseXmlComponent {
3935
+ connections;
3936
+ constructor(connections) {
3937
+ super("connections");
3938
+ this.connections = connections;
3939
+ }
3940
+ toXml(_context) {
3941
+ const p = ["<connections xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">"];
3942
+ for (const c of this.connections) {
3943
+ const cAttrs = { id: c.id };
3944
+ if (c.name !== void 0) cAttrs.name = c.name;
3945
+ if (c.type !== void 0) cAttrs.type = c.type;
3946
+ if (c.refreshOnLoad) cAttrs.refreshOnLoad = 1;
3947
+ if (c.refreshedVersion !== void 0) cAttrs.refreshedVersion = c.refreshedVersion;
3948
+ else cAttrs.refreshedVersion = 6;
3949
+ if (c.backgroundRefresh) cAttrs.backgroundRefresh = 1;
3950
+ if (c.saveData === false) cAttrs.saveData = 0;
3951
+ if (c.savePassword) cAttrs.savePassword = 1;
3952
+ if (c.description !== void 0) cAttrs.description = c.description;
3953
+ if (c.credentials !== void 0) cAttrs.credentials = c.credentials;
3954
+ if (c.interval !== void 0) cAttrs.interval = c.interval;
3955
+ if (c.keepAlive) cAttrs.keepAlive = 1;
3956
+ if (c.new) cAttrs.new = 1;
3957
+ if (c.odcFile !== void 0) cAttrs.odcFile = c.odcFile;
3958
+ if (c.onlyUseConnectionFile) cAttrs.onlyUseConnectionFile = 1;
3959
+ if (c.reconnectionMethod !== void 0) cAttrs.reconnectionMethod = c.reconnectionMethod;
3960
+ if (c.singleSignOnId !== void 0) cAttrs.singleSignOnId = c.singleSignOnId;
3961
+ const children = [];
3962
+ if (c.dbPr) {
3963
+ const dbAttrs = { connection: c.dbPr.connection };
3964
+ if (c.dbPr.command !== void 0) dbAttrs.command = c.dbPr.command;
3965
+ if (c.dbPr.commandType !== void 0) dbAttrs.commandType = c.dbPr.commandType;
3966
+ if (c.dbPr.serverCommand !== void 0) dbAttrs.serverCommand = c.dbPr.serverCommand;
3967
+ children.push(`<dbPr${attrs(dbAttrs)}/>`);
3968
+ }
3969
+ if (c.webPr) {
3970
+ const wpAttrs = { url: c.webPr.url };
3971
+ if (c.webPr.sourceData) wpAttrs.sourceData = 1;
3972
+ if (c.webPr.htmlFormat !== void 0) wpAttrs.htmlFormat = c.webPr.htmlFormat;
3973
+ if (c.webPr.consecutive) wpAttrs.consecutive = 1;
3974
+ if (c.webPr.firstRowHeader) wpAttrs.firstRowHeader = 1;
3975
+ if (c.webPr.parsePre) wpAttrs.parsePre = 1;
3976
+ if (c.webPr.xl2000) wpAttrs.xl2000 = 1;
3977
+ if (c.webPr.editPage !== void 0) wpAttrs.editPage = c.webPr.editPage;
3978
+ if (c.webPr.firstRow) wpAttrs.firstRow = 1;
3979
+ if (c.webPr.post) wpAttrs.post = 1;
3980
+ if (c.webPr.textDates) wpAttrs.textDates = 1;
3981
+ if (c.webPr.xl97) wpAttrs.xl97 = 1;
3982
+ const wpChildren = [];
3983
+ if (c.webPr.htmlTables && c.webPr.htmlTables.length > 0) wpChildren.push(`<tables>${c.webPr.htmlTables.map((t) => `<x v="${escapeXml(t)}"/>`).join("")}</tables>`);
3984
+ if (c.webPr.textFields && c.webPr.textFields.length > 0) wpChildren.push(buildTextFields(c.webPr.textFields));
3985
+ if (wpChildren.length > 0) children.push(`<webPr${attrs(wpAttrs)}>${wpChildren.join("")}</webPr>`);
3986
+ else children.push(`<webPr${attrs(wpAttrs)}/>`);
3987
+ }
3988
+ if (c.textPr) {
3989
+ const tpAttrs = {};
3990
+ if (c.textPr.codePage !== void 0) tpAttrs.codePage = c.textPr.codePage;
3991
+ if (c.textPr.characterSet !== void 0) tpAttrs.characterSet = c.textPr.characterSet;
3992
+ if (c.textPr.sourceFile !== void 0) tpAttrs.sourceFile = c.textPr.sourceFile;
3993
+ if (c.textPr.delimited !== void 0) tpAttrs.delimited = c.textPr.delimited ? 1 : 0;
3994
+ if (c.textPr.tab !== void 0) tpAttrs.tab = c.textPr.tab ? 1 : 0;
3995
+ if (c.textPr.space !== void 0) tpAttrs.space = c.textPr.space ? 1 : 0;
3996
+ if (c.textPr.comma !== void 0) tpAttrs.comma = c.textPr.comma ? 1 : 0;
3997
+ if (c.textPr.semicolon !== void 0) tpAttrs.semicolon = c.textPr.semicolon ? 1 : 0;
3998
+ if (c.textPr.custom !== void 0) tpAttrs.custom = c.textPr.custom;
3999
+ if (c.textPr.decimal !== void 0) tpAttrs.decimal = c.textPr.decimal;
4000
+ if (c.textPr.thousands !== void 0) tpAttrs.thousands = c.textPr.thousands;
4001
+ if (c.textPr.trailingMinus !== void 0) tpAttrs.trailingMinus = c.textPr.trailingMinus ? 1 : 0;
4002
+ if (c.textPr.delimiter !== void 0) tpAttrs.delimiter = c.textPr.delimiter;
4003
+ if (c.textPr.fileType !== void 0) tpAttrs.fileType = c.textPr.fileType;
4004
+ if (c.textPr.firstRow) tpAttrs.firstRow = 1;
4005
+ if (c.textPr.qualifier !== void 0) tpAttrs.qualifier = c.textPr.qualifier;
4006
+ const tpChildren = [];
4007
+ if (c.textPr.textFields && c.textPr.textFields.length > 0) tpChildren.push(buildTextFields(c.textPr.textFields));
4008
+ if (tpChildren.length > 0) children.push(`<textPr${attrs(tpAttrs)}>${tpChildren.join("")}</textPr>`);
4009
+ else children.push(`<textPr${attrs(tpAttrs)}/>`);
4010
+ }
4011
+ if (c.parameters && c.parameters.length > 0) {
4012
+ const paramParts = [`<parameters count="${c.parameters.length}">`];
4013
+ for (const param of c.parameters) {
4014
+ const paramAttrs = { name: param.name };
4015
+ if (param.sqlType !== void 0) paramAttrs.sqlType = param.sqlType;
4016
+ if (param.characterSet !== void 0) paramAttrs.characterSet = param.characterSet;
4017
+ if (param.stringValue !== void 0) paramAttrs.stringValue = param.stringValue;
4018
+ if (param.integerValue !== void 0) paramAttrs.integerValue = param.integerValue;
4019
+ if (param.booleanValue !== void 0) paramAttrs.booleanValue = param.booleanValue ? 1 : 0;
4020
+ if (param.refreshOnChange) paramAttrs.refreshOnChange = 1;
4021
+ if (param.prompt) paramAttrs.prompt = 1;
4022
+ if (param.integer) paramAttrs.integer = 1;
4023
+ if (param.reference !== void 0) paramAttrs.reference = param.reference;
4024
+ if (param.parameterType !== void 0) paramAttrs.parameterType = param.parameterType;
4025
+ paramParts.push(`<parameter${attrs(paramAttrs)}/>`);
4026
+ }
4027
+ paramParts.push("</parameters>");
4028
+ children.push(paramParts.join(""));
4029
+ }
4030
+ if (children.length > 0) p.push(`<connection${attrs(cAttrs)}>${children.join("")}</connection>`);
4031
+ else p.push(`<connection${attrs(cAttrs)}/>`);
4032
+ }
4033
+ p.push("</connections>");
4034
+ return p.join("");
4035
+ }
4036
+ };
4037
+ function buildTextFields(fields) {
4038
+ const parts = [`<textFields count="${fields.length}">`];
4039
+ for (const f of fields) {
4040
+ const fAttrs = { type: f.type };
4041
+ if (f.dataType !== void 0) fAttrs.dataType = f.dataType;
4042
+ parts.push(`<textField${attrs(fAttrs)}/>`);
4043
+ }
4044
+ parts.push("</textFields>");
4045
+ return parts.join("");
4046
+ }
4047
+ //#endregion
4048
+ //#region src/file/xml-mapping/xml-mapping-xml.ts
4049
+ /**
4050
+ * XML Mapping elements — produces XML spreadsheet mapping elements.
4051
+ *
4052
+ * Reference: OOXML transitional, sml.xsd
4053
+ * CT_MapInfo, CT_Schema, CT_Map, CT_DataBinding,
4054
+ * CT_SingleXmlCells, CT_SingleXmlCell, CT_XmlCellPr, CT_XmlColumnPr, CT_XmlPr
4055
+ *
4056
+ * @module
4057
+ */
4058
+ function schemaToXml(s) {
4059
+ const a = { ID: s.id };
4060
+ if (s.schemaRef !== void 0) a.SchemaRef = s.schemaRef;
4061
+ if (s.namespace !== void 0) a.Namespace = s.namespace;
4062
+ if (s.schemaLanguage !== void 0) a.SchemaLanguage = s.schemaLanguage;
4063
+ if (s.schemaID !== void 0) a.SchemaID = s.schemaID;
4064
+ if (s.elementFormDefault !== void 0) a.ElementFormDefault = s.elementFormDefault;
4065
+ if (s.attributeFormDefault !== void 0) a.AttributeFormDefault = s.attributeFormDefault;
4066
+ return `<Schema${attrs(a)}/>`;
4067
+ }
4068
+ function dataBindingToXml(db) {
4069
+ const a = {};
4070
+ if (db.dataBindingName !== void 0) a.DataBindingName = db.dataBindingName;
4071
+ if (db.fileBinding !== void 0) a.FileBinding = db.fileBinding ? 1 : 0;
4072
+ if (db.fileBindingName !== void 0) a.FileBindingName = db.fileBindingName;
4073
+ if (db.connectionID !== void 0) a.ConnectionID = db.connectionID;
4074
+ if (db.dataBindingLoadMode !== void 0) a.DataBindingLoadMode = db.dataBindingLoadMode;
4075
+ return `<DataBinding${attrs(a)}/>`;
4076
+ }
4077
+ function mapToXml(m) {
4078
+ const a = {
4079
+ ID: m.id,
4080
+ Name: m.name,
4081
+ RootElement: m.rootElement,
4082
+ SchemaID: m.schemaID
4083
+ };
4084
+ if (m.showImportExportValidationErrors !== void 0) a.ShowImportExportValidationErrors = m.showImportExportValidationErrors ? 1 : 0;
4085
+ if (m.append !== void 0) a.Append = m.append ? 1 : 0;
4086
+ if (m.dataBindingLoadMode !== void 0) a.DataBindingLoadMode = m.dataBindingLoadMode;
4087
+ if (m.autoFit !== void 0) a.AutoFit = m.autoFit ? 1 : 0;
4088
+ if (m.fileBinding !== void 0) a.FileBinding = m.fileBinding ? 1 : 0;
4089
+ if (m.fileBindingName !== void 0) a.FileBindingName = m.fileBindingName;
4090
+ if (m.preserveFormat !== void 0) a.PreserveFormat = m.preserveFormat ? 1 : 0;
4091
+ if (m.preserveSortAFLayout !== void 0) a.PreserveSortAFLayout = m.preserveSortAFLayout ? 1 : 0;
4092
+ const children = [];
4093
+ if (m.dataBinding) children.push(dataBindingToXml(m.dataBinding));
4094
+ if (children.length > 0) return `<Map${attrs(a)}>${children.join("")}</Map>`;
4095
+ return `<Map${attrs(a)}/>`;
4096
+ }
4097
+ function xmlPrToXml(xp) {
4098
+ const a = {
4099
+ mapId: xp.mapId,
4100
+ xpath: xp.xpath,
4101
+ xmlDataType: xp.xmlDataType
4102
+ };
4103
+ if (xp.xmlElement !== void 0) a.xmlElement = xp.xmlElement;
4104
+ return `<xmlPr${attrs(a)}/>`;
4105
+ }
4106
+ function xmlCellPrToXml(xcp) {
4107
+ const a = { id: xcp.id };
4108
+ if (xcp.uniqueName !== void 0) a.uniqueName = xcp.uniqueName;
4109
+ return `<xmlCellPr${attrs(a)}>${xmlPrToXml(xcp.xmlPr)}</xmlCellPr>`;
4110
+ }
4111
+ function singleXmlCellToXml(sxc) {
4112
+ return `<singleXmlCell${attrs({
4113
+ id: sxc.id,
4114
+ r: sxc.r,
4115
+ connectionId: sxc.connectionId
4116
+ })}>${xmlCellPrToXml(sxc.xmlCellPr)}</singleXmlCell>`;
4117
+ }
4118
+ var MapInfoXml = class extends BaseXmlComponent {
4119
+ options;
4120
+ constructor(options) {
4121
+ super("MapInfo");
4122
+ this.options = options;
4123
+ }
4124
+ toXml(_context) {
4125
+ const p = ["<MapInfo xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\""];
4126
+ p.push(` SelectionNamespaces="${this.options.selectionNamespaces}">`);
4127
+ for (const s of this.options.schemas) p.push(schemaToXml(s));
4128
+ for (const m of this.options.maps) p.push(mapToXml(m));
4129
+ p.push("</MapInfo>");
4130
+ return p.join("");
4131
+ }
4132
+ };
4133
+ var SingleXmlCellsXml = class extends BaseXmlComponent {
4134
+ cells;
4135
+ constructor(cells) {
4136
+ super("singleXmlCells");
4137
+ this.cells = cells;
4138
+ }
4139
+ toXml(_context) {
4140
+ const p = ["<singleXmlCells xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">"];
4141
+ for (const cell of this.cells) p.push(singleXmlCellToXml(cell));
4142
+ p.push("</singleXmlCells>");
4143
+ return p.join("");
4144
+ }
4145
+ };
4146
+ var XmlColumnPrXml = class extends BaseXmlComponent {
4147
+ options;
4148
+ constructor(options) {
4149
+ super("xmlColumnPr");
4150
+ this.options = options;
4151
+ }
4152
+ toXml(_context) {
4153
+ return `<xmlColumnPr${attrs({
4154
+ xpath: this.options.xpath,
4155
+ xmlDataType: this.options.xmlDataType,
4156
+ mapId: this.options.mapId,
4157
+ denormalized: this.options.denormalized ? 1 : void 0
4158
+ })}/>`;
4159
+ }
4160
+ };
4161
+ //#endregion
4162
+ //#region src/file/calc-chain.ts
4163
+ /**
4164
+ * Calculation Chain — generates xl/calcChain.xml.
4165
+ *
4166
+ * The calculation chain lists formula cells in calculation order,
4167
+ * enabling faster recalculation in spreadsheet applications.
4168
+ *
4169
+ * Reference: OOXML transitional, sml.xsd, CT_CalcChain / CT_CalcCell
4170
+ *
4171
+ * @module
4172
+ */
4173
+ var CalcChain = class extends BaseXmlComponent {
4174
+ cells = [];
4175
+ constructor() {
4176
+ super("calcChain");
4177
+ }
4178
+ addCell(cell) {
4179
+ this.cells.push(cell);
4180
+ }
4181
+ get count() {
4182
+ return this.cells.length;
4183
+ }
4184
+ toXml(_context) {
4185
+ const parts = ["<calcChain xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">"];
4186
+ for (const cell of this.cells) {
4187
+ const cellAttrs = {
4188
+ r: cell.reference,
4189
+ i: cell.sheetIndex
4190
+ };
4191
+ if (cell.array) cellAttrs.a = true;
4192
+ parts.push(`<c${attrs(cellAttrs)}/>`);
4193
+ }
4194
+ parts.push("</calcChain>");
4195
+ return parts.join("");
4196
+ }
4197
+ };
4198
+ //#endregion
4199
+ //#region src/file/chartsheet/chartsheet.ts
4200
+ /**
4201
+ * Chartsheet XML generator — produces xl/chartsheets/sheetN.xml.
4202
+ *
4203
+ * A chartsheet is a worksheet that contains only a chart (no cells).
4204
+ *
4205
+ * Reference: OOXML transitional, sml.xsd, CT_Chartsheet
4206
+ *
4207
+ * @module
4208
+ */
4209
+ var Chartsheet = class extends BaseXmlComponent {
4210
+ opts;
4211
+ drawingRId = "rId1";
4212
+ constructor(options) {
4213
+ super("chartsheet");
4214
+ this.opts = options;
4215
+ }
4216
+ setDrawingRId(rId) {
4217
+ this.drawingRId = rId;
4218
+ }
4219
+ toXml(_context) {
4220
+ const p = ["<chartsheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"];
4221
+ if (this.opts.tabColor || this.opts.published) {
4222
+ const prAttrs = [];
4223
+ if (this.opts.tabColor) prAttrs.push(`<tabColor${attrs({ rgb: this.opts.tabColor })}/>`);
4224
+ const spAttr = this.opts.published ? " published=\"1\"" : "";
4225
+ p.push(`<sheetPr${spAttr}>${prAttrs.join("")}</sheetPr>`);
4226
+ }
4227
+ const svAttrs = ["workbookViewId=\"0\""];
4228
+ if (this.opts.zoomToFit) svAttrs.push("zoomToFit=\"1\"");
4229
+ p.push(`<sheetViews><sheetView ${svAttrs.join(" ")}/></sheetViews>`);
4230
+ if (this.opts.sheetProtection) {
4231
+ const sp = this.opts.sheetProtection;
4232
+ const spAttrs = [];
4233
+ if (sp.content) spAttrs.push(` content="1"`);
4234
+ if (sp.objects) spAttrs.push(` objects="1"`);
4235
+ if (spAttrs.length > 0) p.push(`<sheetProtection${spAttrs.join("")}/>`);
4236
+ }
4237
+ if (this.opts.pageMargins) {
4238
+ const pm = this.opts.pageMargins;
4239
+ p.push(`<pageMargins${attrs({
4240
+ left: pm.left ?? .7,
4241
+ right: pm.right ?? .7,
4242
+ top: pm.top ?? .75,
4243
+ bottom: pm.bottom ?? .75,
4244
+ header: pm.header ?? .3,
4245
+ footer: pm.footer ?? .3
4246
+ })}/>`);
4247
+ }
4248
+ if (this.opts.pageSetup) {
4249
+ const ps = this.opts.pageSetup;
4250
+ p.push(`<pageSetup${attrs({
4251
+ paperSize: ps.paperSize,
4252
+ orientation: ps.orientation,
4253
+ horizontalDpi: ps.horizontalDpi,
4254
+ verticalDpi: ps.verticalDpi,
4255
+ copies: ps.copies
4256
+ })}/>`);
4257
+ }
4258
+ if (this.opts.headerFooter) {
4259
+ const hf = this.opts.headerFooter;
4260
+ const hfParts = [];
4261
+ if (hf.differentFirst) hfParts.push(` differentFirst="1"`);
4262
+ if (hf.differentOddEven) hfParts.push(` differentOddEven="1"`);
4263
+ const hfContent = [];
4264
+ if (hf.oddHeader) hfContent.push(`<oddHeader>${escapeXml(hf.oddHeader)}</oddHeader>`);
4265
+ if (hf.oddFooter) hfContent.push(`<oddFooter>${escapeXml(hf.oddFooter)}</oddFooter>`);
4266
+ p.push(`<headerFooter${hfParts.join("")}>${hfContent.join("")}</headerFooter>`);
4267
+ }
4268
+ p.push(`<drawing r:id="${escapeXml(this.drawingRId)}"/>`);
4269
+ p.push("</chartsheet>");
4270
+ return p.join("");
4271
+ }
4272
+ };
4273
+ //#endregion
4274
+ //#region src/file/comments.ts
4275
+ /**
4276
+ * Generates xl/comments{n}.xml — cell comment data.
4277
+ *
4278
+ * @module
4279
+ */
4280
+ var Comments = class extends BaseXmlComponent {
4281
+ entries;
4282
+ constructor(entries) {
4283
+ super("comments");
4284
+ this.entries = entries;
4285
+ }
4286
+ toXml(_context) {
4287
+ const authors = this.collectAuthors();
4288
+ const p = [`<comments xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"${this.entries.some((e) => e.commentPr) ? " xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\"" : ""}>`, `<authors>`];
4289
+ for (const author of authors) p.push(`<author>${escapeXml(author)}</author>`);
4290
+ p.push("</authors><commentList>");
4291
+ for (const entry of this.entries) {
4292
+ const authorId = authors.indexOf(entry.author);
4293
+ const textXml = typeof entry.text === "string" ? `<t>${escapeXml(entry.text)}</t>` : buildRstXml(entry.text);
4294
+ const commentPrXml = this.buildCommentPrXml(entry);
4295
+ p.push(`<comment ref="${entry.cell}" authorId="${authorId}"><text>${textXml}</text>${commentPrXml}</comment>`);
4296
+ }
4297
+ p.push("</commentList></comments>");
4298
+ return p.join("");
4299
+ }
4300
+ /** Build CT_CommentPr XML. Returns empty string if commentPr is not set. */
4301
+ buildCommentPrXml(entry) {
4302
+ const cp = entry.commentPr;
4303
+ if (!cp) return "";
4304
+ const attrs = [];
4305
+ if (cp.locked === false) attrs.push("locked=\"0\"");
4306
+ if (cp.defaultSize === false) attrs.push("defaultSize=\"0\"");
4307
+ if (cp.print === false) attrs.push("print=\"0\"");
4308
+ if (cp.disabled) attrs.push("disabled=\"1\"");
4309
+ if (cp.autoFill === false) attrs.push("autoFill=\"0\"");
4310
+ if (cp.autoLine === false) attrs.push("autoLine=\"0\"");
4311
+ if (cp.altText) attrs.push(`altText="${escapeXml(cp.altText)}"`);
4312
+ if (cp.textHAlign && cp.textHAlign !== "left") attrs.push(`textHAlign="${cp.textHAlign}"`);
4313
+ if (cp.textVAlign && cp.textVAlign !== "top") attrs.push(`textVAlign="${cp.textVAlign}"`);
4314
+ if (cp.lockText === false) attrs.push("lockText=\"0\"");
4315
+ if (cp.justLastX) attrs.push("justLastX=\"1\"");
4316
+ if (cp.autoScale) attrs.push("autoScale=\"1\"");
4317
+ const anchorXml = this.buildAnchorXml(entry.cell, cp.anchor);
4318
+ return `<commentPr${attrs.length ? ` ${attrs.join(" ")}` : ""}>${anchorXml}</commentPr>`;
4319
+ }
4320
+ /** Build CT_ObjectAnchor with required xdr:from/xdr:to markers. */
4321
+ buildAnchorXml(cell, anchor) {
4322
+ const col = cell.charCodeAt(0) - 65;
4323
+ const row = parseInt(cell.slice(1), 10) - 1;
4324
+ const toCol = col + 2;
4325
+ const toRow = row + 2;
4326
+ const anchorAttrs = [];
4327
+ if (anchor?.moveWithCells) anchorAttrs.push(" moveWithCells=\"1\"");
4328
+ if (anchor?.sizeWithCells) anchorAttrs.push(" sizeWithCells=\"1\"");
4329
+ return `<anchor${anchorAttrs.join("")}><xdr:from><xdr:col>${col}</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>${row}</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from><xdr:to><xdr:col>${toCol}</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>${toRow}</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to></anchor>`;
4330
+ }
4331
+ collectAuthors() {
4332
+ const seen = /* @__PURE__ */ new Set();
4333
+ const result = [];
4334
+ for (const entry of this.entries) if (!seen.has(entry.author)) {
4335
+ seen.add(entry.author);
4336
+ result.push(entry.author);
4337
+ }
4338
+ return result.length > 0 ? result : [""];
4339
+ }
4340
+ };
4341
+ //#endregion
4342
+ //#region src/file/drawing/drawing.ts
4343
+ /**
4344
+ * XLSX Drawing component — generates xl/drawings/drawing{n}.xml.
4345
+ *
4346
+ * Uses the spreadsheetDrawing namespace (default, no prefix) for anchoring
4347
+ * images and charts to worksheet cells.
4348
+ *
4349
+ * @module
4350
+ */
4351
+ const XDR_NS = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing";
4352
+ const A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main";
4353
+ const R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
4354
+ const C_URI = "http://schemas.openxmlformats.org/drawingml/2006/chart";
4355
+ var Drawing = class extends BaseXmlComponent {
4356
+ images;
4357
+ charts;
4358
+ constructor(images, charts = []) {
4359
+ super("wsDr");
4360
+ this.images = images;
4361
+ this.charts = charts;
4362
+ }
4363
+ toXml(_context) {
4364
+ const p = [`<wsDr xmlns="${XDR_NS}" xmlns:a="${A_NS}" xmlns:r="${R_NS}">`];
4365
+ let id = 1;
4366
+ for (const img of this.images) {
4367
+ p.push(`<twoCellAnchor editAs="oneCell"><from><col>${img.col - 1}</col><colOff>${img.colOffset ?? 0}</colOff><row>${img.row - 1}</row><rowOff>${img.rowOffset ?? 0}</rowOff></from>`, `<to><col>${img.col}</col><colOff>0</colOff><row>${img.row}</row><rowOff>0</rowOff></to>`, `<pic><nvPicPr><cNvPr id="${id}" name="Picture ${id}"/><cNvPicPr preferRelativeResize="1"/></nvPicPr>`, `<blipFill><a:blip r:embed="${img.rId}"/><a:stretch><a:fillRect/></a:stretch></blipFill>`, `<spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="400000" cy="300000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></spPr></pic>`, `<clientData fLocksWithSheet="${img.locksWithSheet !== false ? 1 : 0}" fPrintsWithSheet="${img.printsWithSheet !== false ? 1 : 0}"/></twoCellAnchor>`);
4368
+ id++;
4369
+ }
4370
+ for (const chart of this.charts) {
4371
+ p.push(`<twoCellAnchor editAs="oneCell"><from><col>${chart.col - 1}</col><colOff>${chart.colOffset ?? 0}</colOff><row>${chart.row - 1}</row><rowOff>${chart.rowOffset ?? 0}</rowOff></from>`, `<to><col>${chart.col + 8}</col><colOff>0</colOff><row>${chart.row + 15}</row><rowOff>0</rowOff></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}" r:id="${chart.rId}"/></a:graphicData></a:graphic></graphicFrame>`, `<clientData fLocksWithSheet="${chart.locksWithSheet !== false ? 1 : 0}" fPrintsWithSheet="${chart.printsWithSheet !== false ? 1 : 0}"/></twoCellAnchor>`);
4372
+ id++;
4373
+ }
4374
+ p.push("</wsDr>");
4375
+ return p.join("");
4376
+ }
4377
+ };
4378
+ //#endregion
4379
+ //#region src/file/external-link/external-link-xml.ts
4380
+ /**
4381
+ * External Link XML generator — produces xl/externalLinks/externalLinkN.xml.
4382
+ *
4383
+ * Reference: OOXML transitional, sml.xsd, CT_ExternalLink
4384
+ *
4385
+ * @module
4386
+ */
4387
+ var ExternalLinkXml = class extends BaseXmlComponent {
4388
+ opts;
4389
+ constructor(options) {
4390
+ super("externalLink");
4391
+ this.opts = options;
4392
+ }
4393
+ toXml(_context) {
4394
+ const p = ["<externalLink xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"];
4395
+ if (this.opts.externalBook) {
4396
+ const book = this.opts.externalBook;
4397
+ const bookParts = [];
4398
+ if (book.sheetNames && book.sheetNames.length > 0) {
4399
+ bookParts.push("<sheetNames>");
4400
+ for (const name of book.sheetNames) bookParts.push(`<sheetName val="${escapeXml(name)}"/>`);
4401
+ bookParts.push("</sheetNames>");
4402
+ }
4403
+ if (book.definedNames && book.definedNames.length > 0) {
4404
+ bookParts.push("<definedNames>");
4405
+ for (const dn of book.definedNames) {
4406
+ const dnAttrs = { name: dn.name };
4407
+ if (dn.refersTo !== void 0) dnAttrs.refersTo = dn.refersTo;
4408
+ if (dn.sheetId !== void 0) dnAttrs.sheetId = dn.sheetId;
4409
+ if (dn.publishToServer) dnAttrs.publishToServer = 1;
4410
+ if (dn.vbProcedure) dnAttrs.vbProcedure = 1;
4411
+ if (dn.workbookParameter) dnAttrs.workbookParameter = 1;
4412
+ if (dn.xlm) dnAttrs.xlm = 1;
4413
+ bookParts.push(`<definedName${attrs(dnAttrs)}/>`);
4414
+ }
4415
+ bookParts.push("</definedNames>");
4416
+ }
4417
+ if (book.sheetDataSet && book.sheetDataSet.length > 0) {
4418
+ bookParts.push("<sheetDataSet>");
4419
+ for (const sd of book.sheetDataSet) {
4420
+ const sdAttrs = { sheetId: sd.sheetId };
4421
+ if (sd.refreshError) sdAttrs.refreshError = 1;
4422
+ bookParts.push(`<sheetData${attrs(sdAttrs)}>`);
4423
+ if (sd.rows) for (const row of sd.rows) {
4424
+ bookParts.push(`<row r="${row.rowNumber}">`);
4425
+ if (row.cells) for (const cell of row.cells) {
4426
+ const cellAttrs = { r: cell.reference };
4427
+ if (cell.type !== void 0) cellAttrs.t = cell.type;
4428
+ if (cell.value !== void 0) bookParts.push(`<cell${attrs(cellAttrs)}><v>${escapeXml(cell.value)}</v></cell>`);
4429
+ else bookParts.push(`<cell${attrs(cellAttrs)}/>`);
4430
+ }
4431
+ bookParts.push("</row>");
4432
+ }
4433
+ bookParts.push("</sheetData>");
4434
+ }
4435
+ bookParts.push("</sheetDataSet>");
4436
+ }
4437
+ const ridAttr = this.opts.bookRId ? ` r:id="${this.opts.bookRId}"` : "";
4438
+ p.push(`<externalBook${ridAttr}${bookParts.length > 0 ? `>${bookParts.join("")}</externalBook>` : "/>"}`);
4439
+ }
4440
+ if (this.opts.oleLink) {
4441
+ const oleRId = this.opts.oleRId ? ` r:id="${escapeXml(this.opts.oleRId)}"` : "";
4442
+ const oleChildren = [];
4443
+ if (this.opts.oleLink.oleItems && this.opts.oleLink.oleItems.length > 0) {
4444
+ const itemParts = [`<oleItems>`];
4445
+ for (const item of this.opts.oleLink.oleItems) {
4446
+ const itemAttrs = [`name="${escapeXml(item.name)}"`];
4447
+ if (item.advise) itemAttrs.push("advise=\"1\"");
4448
+ if (item.prefer) itemAttrs.push("prefer=\"1\"");
4449
+ itemParts.push(`<oleItem ${itemAttrs.join(" ")}/>`);
4450
+ }
4451
+ itemParts.push("</oleItems>");
4452
+ oleChildren.push(itemParts.join(""));
4453
+ }
4454
+ if (oleChildren.length > 0) p.push(`<oleLink${oleRId}>${oleChildren.join("")}</oleLink>`);
4455
+ else p.push(`<oleLink${oleRId}/>`);
4456
+ }
4457
+ p.push("</externalLink>");
4458
+ return p.join("");
4459
+ }
4460
+ };
4461
+ //#endregion
1479
4462
  //#region src/file/vml-notes.ts
1480
4463
  var VmlNotes = class {
1481
4464
  comments;
@@ -1537,7 +4520,10 @@ var Compiler = class {
1537
4520
  let globalChartIdx = 0;
1538
4521
  let globalPivotIdx = 0;
1539
4522
  let globalPivotCacheIdx = 0;
4523
+ let globalTableIdx = 0;
1540
4524
  const pivotCacheDataMap = /* @__PURE__ */ new Map();
4525
+ const calcChain = new CalcChain();
4526
+ const allTableParts = [];
1541
4527
  for (let i = 0; i < worksheets.length; i++) {
1542
4528
  const ws = worksheets[i];
1543
4529
  const imgOpts = ws.imageOptions;
@@ -1545,15 +4531,35 @@ var Compiler = class {
1545
4531
  const hlOpts = ws.hyperlinkOptions;
1546
4532
  const sheetName = file.worksheetConfigs[i]?.name ?? `Sheet${i + 1}`;
1547
4533
  let sheetXml = fmt(ws);
4534
+ const sheetIdx = i + 1;
4535
+ const wsRows = ws.worksheetRows;
4536
+ for (let ri = 0; ri < wsRows.length; ri++) {
4537
+ const rowOpts = wsRows[ri];
4538
+ const rowNumber = rowOpts.rowNumber ?? ri + 1;
4539
+ if (!rowOpts.cells) continue;
4540
+ for (let ci = 0; ci < rowOpts.cells.length; ci++) {
4541
+ const cell = rowOpts.cells[ci];
4542
+ if (!cell.formula) continue;
4543
+ const ref = cell.reference ?? columnToLetter$1(ci + 1) + rowNumber;
4544
+ calcChain.addCell({
4545
+ reference: ref,
4546
+ sheetIndex: sheetIdx,
4547
+ array: cell.formula.type === "array"
4548
+ });
4549
+ }
4550
+ }
1548
4551
  const hasMedia = imgOpts.length > 0 || chartOpts.length > 0;
1549
4552
  const hasExternalHyperlinks = hlOpts.some((h) => h.target.type === "external");
1550
4553
  const commentOpts = ws.commentOptions;
1551
4554
  const hasComments = commentOpts.length > 0;
1552
4555
  const pivotOpts = ws.pivotTables;
1553
4556
  const hasPivots = pivotOpts.length > 0;
4557
+ const tableOpts = ws.tables;
4558
+ const hasTables = tableOpts.length > 0;
4559
+ const bgImg = ws.background;
1554
4560
  let wsRels;
1555
4561
  let nextRid = 0;
1556
- if (hasMedia || hasExternalHyperlinks || hasComments || hasPivots) wsRels = new Relationships();
4562
+ if (hasMedia || hasExternalHyperlinks || hasComments || hasPivots || hasTables || bgImg) wsRels = new Relationships();
1557
4563
  if (hasExternalHyperlinks) for (const hl of hlOpts) {
1558
4564
  if (hl.target.type !== "external") continue;
1559
4565
  const rid = ++nextRid;
@@ -1633,6 +4639,22 @@ var Compiler = class {
1633
4639
  file.contentTypes.addComments(commentsIdx);
1634
4640
  file.contentTypes.addVmlDrawing();
1635
4641
  }
4642
+ if (bgImg) {
4643
+ const ext = bgImg.type === "jpg" ? "jpeg" : bgImg.type;
4644
+ const mediaKey = `bg_${i}`;
4645
+ const mediaIdx = globalMediaIdx + 1;
4646
+ file.media.addImage(mediaKey, {
4647
+ fileName: `image${mediaIdx}.${ext}`,
4648
+ type: ext,
4649
+ data: bgImg.data,
4650
+ width: 0,
4651
+ height: 0
4652
+ });
4653
+ globalMediaIdx++;
4654
+ const bgRid = ++nextRid;
4655
+ wsRels.addRelationship(bgRid, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", `../media/image${mediaIdx}.${ext}`);
4656
+ sheetXml = sheetXml.replace("<!--BACKGROUND_PICTURE-->", `<picture r:id="rId${bgRid}"/>`);
4657
+ }
1636
4658
  if (hasPivots) for (const pt of pivotOpts) {
1637
4659
  globalPivotIdx++;
1638
4660
  const pivotIdx = globalPivotIdx;
@@ -1693,6 +4715,24 @@ var Compiler = class {
1693
4715
  wsRels.addRelationship(ptRid, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable", `../pivotTables/pivotTable${pivotIdx}.xml`);
1694
4716
  file.contentTypes.addPivotTable(pivotIdx);
1695
4717
  }
4718
+ const wsTableParts = [];
4719
+ if (hasTables) for (const tbl of tableOpts) {
4720
+ globalTableIdx++;
4721
+ const tableIdx = globalTableIdx;
4722
+ const tableXml = new TableXml({
4723
+ ...tbl,
4724
+ id: tbl.id ?? tableIdx
4725
+ });
4726
+ mapping[`Table${tableIdx}`] = {
4727
+ data: fmt(tableXml),
4728
+ path: `xl/tables/table${tableIdx}.xml`
4729
+ };
4730
+ const tblRid = ++nextRid;
4731
+ wsRels.addRelationship(tblRid, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/table", `../tables/table${tableIdx}.xml`);
4732
+ wsTableParts.push({ rId: `rId${tblRid}` });
4733
+ allTableParts.push({ rId: `rId${tblRid}` });
4734
+ file.contentTypes.addTable(tableIdx);
4735
+ }
1696
4736
  if (hasPivots) {
1697
4737
  const rendered = renderPivotSheetData(pivotOpts, worksheets, file.sharedStrings, file.worksheetConfigs, sheetName);
1698
4738
  if (rendered.sheetData.length > 0) {
@@ -1700,6 +4740,10 @@ var Compiler = class {
1700
4740
  if (!sheetXml.includes("<dimension")) sheetXml = sheetXml.replace("<sheetViews", `<dimension ref="${rendered.dimensionRef}"/><sheetViews`);
1701
4741
  }
1702
4742
  }
4743
+ if (wsTableParts.length > 0) {
4744
+ const tablePartsXml = WorkbookXml.buildTablePartsXml(wsTableParts);
4745
+ sheetXml = sheetXml.slice(0, -12) + tablePartsXml + "</worksheet>";
4746
+ }
1703
4747
  if (wsRels) mapping[`WorksheetRels${i}`] = {
1704
4748
  data: fmt(wsRels),
1705
4749
  path: `xl/worksheets/_rels/sheet${i + 1}.xml.rels`
@@ -1709,8 +4753,83 @@ var Compiler = class {
1709
4753
  path: `xl/worksheets/sheet${i + 1}.xml`
1710
4754
  };
1711
4755
  }
4756
+ const chartsheetConfigs = file.chartsheetConfigs;
4757
+ for (let i = 0; i < chartsheetConfigs.length; i++) {
4758
+ const csOpts = chartsheetConfigs[i];
4759
+ const chartsheet = new Chartsheet(csOpts);
4760
+ const chartDef = csOpts.chart;
4761
+ const csChartGlobalIdx = file.charts.array.length;
4762
+ const csChartKey = `cs_chart_${csChartGlobalIdx}`;
4763
+ file.charts.addChart(csChartKey, {
4764
+ key: csChartKey,
4765
+ chartSpace: new ChartSpace({
4766
+ type: chartDef.type,
4767
+ title: chartDef.title,
4768
+ categories: chartDef.categories,
4769
+ series: chartDef.series
4770
+ })
4771
+ });
4772
+ const csRels = new Relationships();
4773
+ const csDrawingIdx = i + 1;
4774
+ csRels.addRelationship(1, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing", `../drawings/drawing${csDrawingIdx}.xml`);
4775
+ chartsheet.setDrawingRId("rId1");
4776
+ const csDrawingRels = new Relationships();
4777
+ csDrawingRels.addRelationship(1, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart", `../charts/chart${csChartGlobalIdx + 1}.xml`);
4778
+ const csDrawingXml = `<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><xdr:absoluteAnchor><xdr:pos x="0" y="0"/><xdr:ext cx="9308969" cy="6096000"/><xdr:graphicFrame><xdr:nvGraphicFramePr><xdr:cNvPr id="1" name="Chart ${i + 1}"/><xdr:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></xdr:cNvGraphicFramePr></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="9308969" cy="6096000"/></xdr:xfrm><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId1"/></a:graphicData></a:graphic></xdr:graphicFrame><xdr:clientData/></xdr:absoluteAnchor></xdr:wsDr>`;
4779
+ mapping[`ChartsheetDrawing${i}`] = {
4780
+ data: csDrawingXml,
4781
+ path: `xl/drawings/drawing${csDrawingIdx}.xml`
4782
+ };
4783
+ mapping[`ChartsheetDrawingRels${i}`] = {
4784
+ data: fmt(csDrawingRels),
4785
+ path: `xl/drawings/_rels/drawing${csDrawingIdx}.xml.rels`
4786
+ };
4787
+ file.contentTypes.addDrawing(csDrawingIdx);
4788
+ mapping[`ChartsheetRels${i}`] = {
4789
+ data: fmt(csRels),
4790
+ path: `xl/chartsheets/_rels/sheet${i + 1}.xml.rels`
4791
+ };
4792
+ mapping[`Chartsheet${i}`] = {
4793
+ data: chartsheet.toXml(context),
4794
+ path: `xl/chartsheets/sheet${i + 1}.xml`
4795
+ };
4796
+ file.contentTypes.addChartsheet(i + 1);
4797
+ }
4798
+ let workbookXml = fmt(file.workbookXml);
4799
+ const extLinks = file.externalLinks;
4800
+ if (extLinks.length > 0) {
4801
+ const extRefs = [];
4802
+ for (let ei = 0; ei < extLinks.length; ei++) {
4803
+ const elIdx = ei + 1;
4804
+ const elRid = file.workbookRelationships.relationshipCount + 1;
4805
+ file.workbookRelationships.addRelationship(elRid, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink", `externalLinks/externalLink${elIdx}.xml`);
4806
+ const elOpts = extLinks[ei];
4807
+ let bookRId;
4808
+ if (elOpts.externalBook?.target) {
4809
+ const elRels = new Relationships();
4810
+ elRels.addRelationship(1, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath", elOpts.externalBook.target, TargetModeType.EXTERNAL);
4811
+ bookRId = "rId1";
4812
+ mapping[`ExternalLinkRels${elIdx}`] = {
4813
+ data: fmt(elRels),
4814
+ path: `xl/externalLinks/_rels/externalLink${elIdx}.xml.rels`
4815
+ };
4816
+ }
4817
+ const elXml = new ExternalLinkXml({
4818
+ ...elOpts,
4819
+ bookRId
4820
+ });
4821
+ mapping[`ExternalLink${elIdx}`] = {
4822
+ data: fmt(elXml),
4823
+ path: `xl/externalLinks/externalLink${elIdx}.xml`
4824
+ };
4825
+ extRefs.push({ rId: `rId${elRid}` });
4826
+ file.contentTypes.addExternalLink(elIdx);
4827
+ }
4828
+ const extRefsXml = WorkbookXml.buildExternalReferencesXml(extRefs);
4829
+ workbookXml = workbookXml.replace("<!--EXTERNAL_REFS-->", extRefsXml);
4830
+ } else workbookXml = workbookXml.replace("<!--EXTERNAL_REFS-->", "");
1712
4831
  mapping["Workbook"] = {
1713
- data: fmt(file.workbookXml),
4832
+ data: workbookXml,
1714
4833
  path: "xl/workbook.xml"
1715
4834
  };
1716
4835
  mapping["WorkbookRelationships"] = {
@@ -1739,6 +4858,15 @@ var Compiler = class {
1739
4858
  };
1740
4859
  file.contentTypes.addChart(i + 1);
1741
4860
  }
4861
+ if (calcChain.count > 0) {
4862
+ mapping["CalcChain"] = {
4863
+ data: calcChain.toXml(context),
4864
+ path: "xl/calcChain.xml"
4865
+ };
4866
+ file.contentTypes.addCalcChain();
4867
+ const calcChainRid = file.workbookRelationships.relationshipCount + 1;
4868
+ file.workbookRelationships.addRelationship(calcChainRid, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/calcChain", "calcChain.xml");
4869
+ }
1742
4870
  const imageExts = /* @__PURE__ */ new Set();
1743
4871
  for (const img of file.media.array) {
1744
4872
  const ext = img.fileName.endsWith(".png") ? "png" : "jpeg";
@@ -1777,7 +4905,10 @@ function extractPivotSourceData(rows, sourceRef) {
1777
4905
  const colCount = endCol - startCol + 1;
1778
4906
  const headerRow = rows[startRow];
1779
4907
  const fieldNames = [];
1780
- if (headerRow?.cells) for (let c = startCol; c <= endCol && c < headerRow.cells.length; c++) fieldNames.push(String(headerRow.cells[c]?.value ?? `Col${c}`));
4908
+ if (headerRow?.cells) for (let c = startCol; c <= endCol && c < headerRow.cells.length; c++) {
4909
+ const hv = headerRow.cells[c]?.value;
4910
+ fieldNames.push(typeof hv === "string" ? hv : typeof hv === "number" || typeof hv === "boolean" ? String(hv) : `Col${c}`);
4911
+ }
1781
4912
  const records = [];
1782
4913
  for (let r = startRow + 1; r <= endRow; r++) {
1783
4914
  const row = rows[r];
@@ -1787,7 +4918,7 @@ function extractPivotSourceData(rows, sourceRef) {
1787
4918
  const val = row.cells[c]?.value;
1788
4919
  if (typeof val === "number") record.push(val);
1789
4920
  else if (val instanceof Date) record.push(val.getTime());
1790
- else record.push(String(val ?? ""));
4921
+ else record.push(typeof val === "string" ? val : typeof val === "boolean" ? String(val) : "");
1791
4922
  }
1792
4923
  if (record.length === colCount) records.push(record);
1793
4924
  }
@@ -1834,7 +4965,10 @@ function renderPivotSheetData(pivotOpts, worksheets, sharedStrings, worksheetCon
1834
4965
  let group = groupMap.get(groupKey);
1835
4966
  if (!group) {
1836
4967
  group = {
1837
- keys: rowFieldIndices.map((fi) => record[fi]),
4968
+ keys: rowFieldIndices.map((fi) => {
4969
+ const v = record[fi];
4970
+ return typeof v === "string" || typeof v === "number" ? v : String(v ?? "");
4971
+ }),
1838
4972
  values: dataFieldIndices.map(() => [])
1839
4973
  };
1840
4974
  groupMap.set(groupKey, group);
@@ -1927,6 +5061,16 @@ function colIndexToLetterCompiler(col) {
1927
5061
  }
1928
5062
  return result;
1929
5063
  }
5064
+ function columnToLetter$1(col) {
5065
+ let result = "";
5066
+ let n = col;
5067
+ while (n > 0) {
5068
+ const remainder = (n - 1) % 26;
5069
+ result = String.fromCharCode(65 + remainder) + result;
5070
+ n = Math.floor((n - 1) / 26);
5071
+ }
5072
+ return result;
5073
+ }
1930
5074
  //#endregion
1931
5075
  //#region src/export/packer/packer.ts
1932
5076
  /**
@@ -2311,6 +5455,6 @@ function findLocalChild(parent, name) {
2311
5455
  return (parent.elements ?? []).find((el) => localName(el) === name);
2312
5456
  }
2313
5457
  //#endregion
2314
- export { File, File as Workbook, Packer, PatchType, SharedStrings, Styles, columnToLetter, dateToSerialNumber, letterToColumn, parseWorkbook, parseXlsx, patchWorkbook };
5458
+ export { ConnectionsXml, Dialogsheet, File, File as Workbook, MapInfoXml, MetadataXml, Packer, PatchType, PivotFilterType as PivotFilterTypeValue, QueryTableXml, RevisionHeadersXml, RevisionLogXml, SharedStrings, SingleXmlCellsXml, Styles, TableType, TotalsRowFunction, XmlColumnPrXml, columnToLetter, dateToSerialNumber, letterToColumn, parseWorkbook, parseXlsx, patchWorkbook };
2315
5459
 
2316
5460
  //# sourceMappingURL=index.mjs.map