@quirekit/xlsx 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/THIRD_PARTY_NOTICES.md +150 -0
- package/dist/index.d.mts +122 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +19167 -0
- package/dist/index.mjs.map +1 -0
- package/licenses/saxes.LICENSE +64 -0
- package/licenses/xmlchars.LICENSE +18 -0
- package/package.json +52 -3
- package/src/bundle.ts +17 -0
- package/src/comments/legacy/read.ts +68 -0
- package/src/comments/legacy/write.ts +64 -0
- package/src/comments/package/ranges.ts +78 -0
- package/src/comments/package/read.ts +95 -0
- package/src/comments/package/roundtrip.test.ts +106 -0
- package/src/comments/package/write.ts +130 -0
- package/src/comments/thread/read.ts +69 -0
- package/src/comments/thread/write.ts +61 -0
- package/src/comments/types.ts +43 -0
- package/src/comments/xml.ts +50 -0
- package/src/create.ts +13 -0
- package/src/drawing/cache.ts +48 -0
- package/src/drawing/chart.test.ts +96 -0
- package/src/drawing/chart.ts +87 -0
- package/src/drawing/definition/plots.ts +76 -0
- package/src/drawing/definition/read.ts +65 -0
- package/src/drawing/definition/shape.ts +40 -0
- package/src/drawing/definition/types.ts +24 -0
- package/src/drawing/editable-picture.ts +80 -0
- package/src/drawing/graph.ts +148 -0
- package/src/drawing/identity.ts +22 -0
- package/src/drawing/import.ts +133 -0
- package/src/drawing/namespaces.ts +11 -0
- package/src/drawing/picture.test.ts +98 -0
- package/src/drawing/picture.ts +54 -0
- package/src/drawing/placement/anchor.ts +71 -0
- package/src/drawing/placement/axes.ts +113 -0
- package/src/drawing/placement/marker.ts +16 -0
- package/src/drawing/placement/transform.ts +132 -0
- package/src/drawing/placement/types.ts +20 -0
- package/src/drawing/presentation/cartesian/axes.ts +103 -0
- package/src/drawing/presentation/cartesian/plot.ts +109 -0
- package/src/drawing/presentation/cartesian/types.ts +9 -0
- package/src/drawing/presentation/layout.ts +29 -0
- package/src/drawing/presentation/paint.ts +56 -0
- package/src/drawing/presentation/properties.ts +31 -0
- package/src/drawing/read.ts +85 -0
- package/src/drawing/shapes/connector.ts +55 -0
- package/src/drawing/shapes/paint.ts +108 -0
- package/src/drawing/shapes/read.ts +89 -0
- package/src/drawing/shapes/text.ts +89 -0
- package/src/drawing/shapes/types.ts +13 -0
- package/src/drawing/sources.test.ts +27 -0
- package/src/drawing/sources.ts +43 -0
- package/src/drawing/types.ts +54 -0
- package/src/drawing/worksheet-connector.test.ts +135 -0
- package/src/drawing/worksheet-shape.test.ts +61 -0
- package/src/drawing/write/anchor.ts +17 -0
- package/src/drawing/write/axes.ts +23 -0
- package/src/drawing/write/chart.ts +56 -0
- package/src/drawing/write/drawing.ts +61 -0
- package/src/drawing/write/pictures.ts +68 -0
- package/src/drawing/write/series.ts +43 -0
- package/src/drawing/write/shapes.ts +113 -0
- package/src/drawing/write/text.ts +26 -0
- package/src/drawing/write/workbook.test.ts +199 -0
- package/src/drawing/write/workbook.ts +217 -0
- package/src/external-links/formulas.ts +21 -0
- package/src/external-links/read.test.ts +93 -0
- package/src/external-links/read.ts +104 -0
- package/src/external-links/types.ts +9 -0
- package/src/external-links/write.ts +120 -0
- package/src/image/excel.ts +122 -0
- package/src/image/native.ts +21 -0
- package/src/image/ownership.ts +77 -0
- package/src/image/parts.ts +45 -0
- package/src/image/raster.ts +25 -0
- package/src/image/read.test.ts +95 -0
- package/src/image/read.ts +66 -0
- package/src/image/relationships.ts +26 -0
- package/src/image/types.ts +48 -0
- package/src/image/wps.ts +43 -0
- package/src/image/write.test.ts +53 -0
- package/src/image/write.ts +118 -0
- package/src/index.ts +6 -0
- package/src/metadata/dynamic-array.ts +105 -0
- package/src/metadata/package.ts +75 -0
- package/src/metadata/types.ts +7 -0
- package/src/opc/archive.ts +26 -0
- package/src/opc/ownership.ts +40 -0
- package/src/opc/relationships.ts +98 -0
- package/src/opc/revision.ts +28 -0
- package/src/opc/shape.ts +23 -0
- package/src/opc/types.ts +13 -0
- package/src/opc/xml.test.ts +49 -0
- package/src/opc/xml.ts +128 -0
- package/src/optimization/blanks.ts +53 -0
- package/src/optimization/optimize.test.ts +117 -0
- package/src/optimization/optimize.ts +41 -0
- package/src/optimization/package.ts +65 -0
- package/src/optimization/rules.ts +46 -0
- package/src/optimization/styles.ts +76 -0
- package/src/optimization/types.ts +33 -0
- package/src/package/assembly.test.ts +117 -0
- package/src/package/calculation-metadata.test.ts +85 -0
- package/src/package/calculation-metadata.ts +88 -0
- package/src/package/checkboxes.ts +37 -0
- package/src/package/cleanup.test.ts +61 -0
- package/src/package/dashboard.test.ts +53 -0
- package/src/package/dashboard.ts +84 -0
- package/src/package/extensions.ts +16 -0
- package/src/package/merge-recipes.ts +84 -0
- package/src/package/names/conditional.ts +64 -0
- package/src/package/names/defined.test.ts +52 -0
- package/src/package/names/defined.ts +75 -0
- package/src/package/names/filter.ts +68 -0
- package/src/package/names/print-layout.ts +62 -0
- package/src/package/names/print.ts +62 -0
- package/src/package/new.ts +46 -0
- package/src/package/open/appearance.ts +46 -0
- package/src/package/open/directory.ts +61 -0
- package/src/package/open/restrictions.ts +27 -0
- package/src/package/open/snapshot.test.ts +48 -0
- package/src/package/open/snapshot.ts +34 -0
- package/src/package/open/source-write.ts +130 -0
- package/src/package/open/types.ts +73 -0
- package/src/package/open/worksheets.ts +149 -0
- package/src/package/positions.ts +40 -0
- package/src/package/read.ts +143 -0
- package/src/package/save/types.ts +57 -0
- package/src/package/save/worksheets.ts +126 -0
- package/src/package/selection-copy.test.ts +70 -0
- package/src/package/styles.ts +39 -0
- package/src/package/types.ts +52 -0
- package/src/package/workbook-views.ts +34 -0
- package/src/package/worksheets.test.ts +190 -0
- package/src/package/worksheets.ts +162 -0
- package/src/package/write.ts +175 -0
- package/src/pivot/cache/calculated.ts +34 -0
- package/src/pivot/cache/dates.ts +124 -0
- package/src/pivot/cache/groups.ts +11 -0
- package/src/pivot/cache/members.ts +99 -0
- package/src/pivot/cache/numbers.ts +63 -0
- package/src/pivot/cache/read.ts +131 -0
- package/src/pivot/cache/time.ts +20 -0
- package/src/pivot/cache/values.ts +43 -0
- package/src/pivot/cache/write.ts +117 -0
- package/src/pivot/definition/axes.ts +35 -0
- package/src/pivot/definition/dates.ts +87 -0
- package/src/pivot/definition/display.ts +86 -0
- package/src/pivot/definition/extension.ts +57 -0
- package/src/pivot/definition/field-settings/caption.ts +38 -0
- package/src/pivot/definition/field-settings/comparison.ts +47 -0
- package/src/pivot/definition/field-settings/field.ts +66 -0
- package/src/pivot/definition/field-settings/filters.ts +86 -0
- package/src/pivot/definition/field-settings/measure.ts +79 -0
- package/src/pivot/definition/field-settings/types.ts +19 -0
- package/src/pivot/definition/functions.ts +21 -0
- package/src/pivot/definition/items.ts +144 -0
- package/src/pivot/definition/members.ts +98 -0
- package/src/pivot/definition/numbers.ts +19 -0
- package/src/pivot/definition/presentation.ts +52 -0
- package/src/pivot/definition/read.ts +143 -0
- package/src/pivot/definition/report-layout.ts +39 -0
- package/src/pivot/definition/write.ts +157 -0
- package/src/pivot/package/calculated.test.ts +103 -0
- package/src/pivot/package/dates.test.ts +266 -0
- package/src/pivot/package/display.test.ts +133 -0
- package/src/pivot/package/field-settings.test.ts +59 -0
- package/src/pivot/package/layout.test.ts +148 -0
- package/src/pivot/package/measure-settings.test.ts +85 -0
- package/src/pivot/package/members.test.ts +167 -0
- package/src/pivot/package/numbers.test.ts +120 -0
- package/src/pivot/package/read.ts +93 -0
- package/src/pivot/package/roundtrip.test.ts +244 -0
- package/src/pivot/package/write.ts +103 -0
- package/src/pivot/types.ts +36 -0
- package/src/pivot/xml.ts +50 -0
- package/src/presentation.test.ts +186 -0
- package/src/roundtrip.test.ts +72 -0
- package/src/styles/checkbox/bags.ts +85 -0
- package/src/styles/checkbox/style.ts +45 -0
- package/src/styles/checkbox/types.ts +7 -0
- package/src/styles/color.ts +64 -0
- package/src/styles/differential-preview.ts +60 -0
- package/src/styles/differential.ts +119 -0
- package/src/styles/numbers.ts +9 -0
- package/src/styles/parts.ts +107 -0
- package/src/styles/read.ts +95 -0
- package/src/styles/reference.ts +14 -0
- package/src/styles/types.ts +9 -0
- package/src/styles/write.test.ts +88 -0
- package/src/styles/write.ts +162 -0
- package/src/table/conversion.test.ts +73 -0
- package/src/table/definition.ts +89 -0
- package/src/table/filter.ts +42 -0
- package/src/table/ownership.ts +112 -0
- package/src/table/read.test.ts +274 -0
- package/src/table/read.ts +117 -0
- package/src/table/remove.ts +55 -0
- package/src/table/sort.test.ts +79 -0
- package/src/table/styles/builtin.ts +40 -0
- package/src/table/styles/differential.ts +55 -0
- package/src/table/styles/preset-data.ts +17 -0
- package/src/table/styles/presets/dark.ts +104 -0
- package/src/table/styles/presets/light-grid.ts +68 -0
- package/src/table/styles/presets/light.ts +145 -0
- package/src/table/styles/presets/medium-edges.ts +131 -0
- package/src/table/styles/presets/medium.ts +131 -0
- package/src/table/styles/read.ts +70 -0
- package/src/table/styles/types.ts +27 -0
- package/src/table/totals.test.ts +77 -0
- package/src/table/totals.ts +79 -0
- package/src/table/types.ts +21 -0
- package/src/table/write.ts +189 -0
- package/src/types.ts +74 -0
- package/src/value/date.ts +21 -0
- package/src/worksheet/appearance.ts +55 -0
- package/src/worksheet/axis.test.ts +185 -0
- package/src/worksheet/axis.ts +131 -0
- package/src/worksheet/background/read.ts +41 -0
- package/src/worksheet/background/roundtrip.test.ts +77 -0
- package/src/worksheet/background/write.ts +96 -0
- package/src/worksheet/cell-shift.ts +44 -0
- package/src/worksheet/cells.ts +75 -0
- package/src/worksheet/checkbox/formats.ts +53 -0
- package/src/worksheet/checkbox/ranges.ts +112 -0
- package/src/worksheet/checkbox/write.test.ts +62 -0
- package/src/worksheet/conditional/color-scale.ts +61 -0
- package/src/worksheet/conditional/data-bar.ts +76 -0
- package/src/worksheet/conditional/extensions.ts +95 -0
- package/src/worksheet/conditional/icon-reference.ts +69 -0
- package/src/worksheet/conditional/icon-set.test.ts +60 -0
- package/src/worksheet/conditional/icon-set.ts +79 -0
- package/src/worksheet/conditional/preview.ts +44 -0
- package/src/worksheet/conditional/read.ts +185 -0
- package/src/worksheet/conditional/text.test.ts +71 -0
- package/src/worksheet/conditional/text.ts +122 -0
- package/src/worksheet/conditional/threshold.ts +47 -0
- package/src/worksheet/conditional/types.ts +20 -0
- package/src/worksheet/conditional/write-bar.ts +66 -0
- package/src/worksheet/conditional/write.test.ts +218 -0
- package/src/worksheet/conditional/write.ts +103 -0
- package/src/worksheet/copied-axis.ts +70 -0
- package/src/worksheet/data/rows.ts +59 -0
- package/src/worksheet/data/source.test.ts +68 -0
- package/src/worksheet/data/source.ts +31 -0
- package/src/worksheet/data/types.ts +9 -0
- package/src/worksheet/data.test.ts +314 -0
- package/src/worksheet/dimensions/columns.ts +87 -0
- package/src/worksheet/dimensions/write.test.ts +110 -0
- package/src/worksheet/dimensions/write.ts +36 -0
- package/src/worksheet/filters/advanced.test.ts +57 -0
- package/src/worksheet/filters/color.ts +105 -0
- package/src/worksheet/filters/icon.test.ts +83 -0
- package/src/worksheet/filters/icon.ts +39 -0
- package/src/worksheet/filters/read.ts +114 -0
- package/src/worksheet/filters/relative-dates.ts +47 -0
- package/src/worksheet/filters/restore-icons.ts +33 -0
- package/src/worksheet/filters/restore.ts +169 -0
- package/src/worksheet/filters/rules.ts +23 -0
- package/src/worksheet/filters/types.ts +23 -0
- package/src/worksheet/filters/visibility.ts +188 -0
- package/src/worksheet/filters/write.ts +121 -0
- package/src/worksheet/formula/cache.ts +29 -0
- package/src/worksheet/formula/external-results.test.ts +39 -0
- package/src/worksheet/formula/functions.ts +29 -0
- package/src/worksheet/formula/prefix.ts +27 -0
- package/src/worksheet/formula/shared/read.test.ts +121 -0
- package/src/worksheet/formula/shared/read.ts +94 -0
- package/src/worksheet/formula/shared/references.ts +100 -0
- package/src/worksheet/formula/shared/types.ts +21 -0
- package/src/worksheet/formula/spill-read.ts +54 -0
- package/src/worksheet/formula/spill-write.ts +32 -0
- package/src/worksheet/formula/spill.test.ts +101 -0
- package/src/worksheet/formula/write.test.ts +26 -0
- package/src/worksheet/hyperlinks/location.ts +59 -0
- package/src/worksheet/hyperlinks/model.ts +22 -0
- package/src/worksheet/hyperlinks/read.ts +70 -0
- package/src/worksheet/hyperlinks/types.ts +21 -0
- package/src/worksheet/hyperlinks/write.test.ts +203 -0
- package/src/worksheet/hyperlinks/write.ts +51 -0
- package/src/worksheet/merge.test.ts +58 -0
- package/src/worksheet/merge.ts +61 -0
- package/src/worksheet/outline/columns.ts +46 -0
- package/src/worksheet/outline/metadata.ts +68 -0
- package/src/worksheet/outline/native.ts +81 -0
- package/src/worksheet/outline/read.ts +50 -0
- package/src/worksheet/outline/roundtrip.test.ts +73 -0
- package/src/worksheet/outline/types.ts +37 -0
- package/src/worksheet/outline/write.ts +110 -0
- package/src/worksheet/positions.test.ts +46 -0
- package/src/worksheet/positions.ts +48 -0
- package/src/worksheet/print/breaks.ts +72 -0
- package/src/worksheet/print/elements.ts +16 -0
- package/src/worksheet/print/page-text.ts +139 -0
- package/src/worksheet/print/setup.test.ts +141 -0
- package/src/worksheet/print/setup.ts +116 -0
- package/src/worksheet/progress/read.ts +73 -0
- package/src/worksheet/progress/solid.ts +26 -0
- package/src/worksheet/progress/types.ts +11 -0
- package/src/worksheet/progress/write.test.ts +63 -0
- package/src/worksheet/progress/write.ts +46 -0
- package/src/worksheet/read.ts +197 -0
- package/src/worksheet/rich-text.test.ts +41 -0
- package/src/worksheet/rich-text.ts +76 -0
- package/src/worksheet/sort/read.ts +115 -0
- package/src/worksheet/sort/relocate.ts +62 -0
- package/src/worksheet/sort/roundtrip.test.ts +116 -0
- package/src/worksheet/sort/types.ts +11 -0
- package/src/worksheet/sort/write.ts +77 -0
- package/src/worksheet/template.ts +9 -0
- package/src/worksheet/text.ts +33 -0
- package/src/worksheet/validation/extended.ts +36 -0
- package/src/worksheet/validation/image.ts +7 -0
- package/src/worksheet/validation/list-options/portable.ts +90 -0
- package/src/worksheet/validation/list-options/types.ts +14 -0
- package/src/worksheet/validation/list-options/wps.ts +51 -0
- package/src/worksheet/validation/read.ts +162 -0
- package/src/worksheet/validation/text.ts +13 -0
- package/src/worksheet/validation/write.test.ts +259 -0
- package/src/worksheet/validation/write.ts +99 -0
- package/src/worksheet/view/coordinates.ts +39 -0
- package/src/worksheet/view/named/read.ts +116 -0
- package/src/worksheet/view/named/roundtrip.test.ts +136 -0
- package/src/worksheet/view/named/sort.ts +57 -0
- package/src/worksheet/view/named/types.ts +15 -0
- package/src/worksheet/view/named/write.ts +107 -0
- package/src/worksheet/view/named/xml.ts +33 -0
- package/src/worksheet/view/panes.ts +75 -0
- package/src/worksheet/view/read.ts +61 -0
- package/src/worksheet/view/relocate.ts +57 -0
- package/src/worksheet/view/write.test.ts +91 -0
- package/src/worksheet/view/write.ts +57 -0
- package/src/worksheet/write.ts +86 -0
- package/README.md +0 -3
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { isWorkbookWorksheetVisible, validateWorkbookWorksheetName, workbookWorksheetVisibility,
|
|
3
|
+
type WorkbookSheet, type WorkbookWorksheetIdentity } from "@quirekit/workbook";
|
|
4
|
+
import { relationshipsPath } from "../opc/relationships";
|
|
5
|
+
import { child, children, contentTypeNs, packageRelationshipNs, parsePart, readIndex, relationshipNs, rootOf, spreadNs, writePart } from "../opc/xml";
|
|
6
|
+
import { createXlsxWorksheetPart } from "../worksheet/template";
|
|
7
|
+
import { updatePrintNames } from "./names/print";
|
|
8
|
+
import type { XlsxPackage } from "./types";
|
|
9
|
+
import { clearXlsxWorksheetTabSelection, updateXlsxWorkbookViews } from "./workbook-views";
|
|
10
|
+
|
|
11
|
+
/** @param before - Original native sheet directory. @param after - Authored sheet directory.
|
|
12
|
+
* @returns Whether the names, order, and identities are identical. */
|
|
13
|
+
export function sameWorksheetStructure(before: readonly WorkbookWorksheetIdentity[], after: readonly WorkbookWorksheetIdentity[]): boolean {
|
|
14
|
+
return before.length === after.length && before.every((sheet, index) => sheet.id === after[index]?.id && sheet.name === after[index]?.name);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** @param before - Original native sheet directory. @param after - Authored sheet directory.
|
|
18
|
+
* @returns Whether directory structure and visibility are both unchanged. */
|
|
19
|
+
export function sameWorksheetDirectory(before: readonly WorkbookWorksheetIdentity[], after: readonly WorkbookWorksheetIdentity[]): boolean {
|
|
20
|
+
return sameWorksheetStructure(before, after) && before.every((sheet, index) => (sheet.visibility ?? "visible") === (after[index]?.visibility ?? "visible"));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @param directory - Worksheets to register. @param original - Native paths keyed by their unchanged identities. */
|
|
24
|
+
export function assertWorksheetDirectory(directory: readonly WorkbookSheet[], original: ReadonlyMap<string, string>): void {
|
|
25
|
+
if (!directory.length || new Set(directory.map(sheet => sheet.id)).size !== directory.length
|
|
26
|
+
|| new Set(directory.map(sheet => sheet.name.toUpperCase())).size !== directory.length) {
|
|
27
|
+
throw new Error("工作簿应至少保留一张工作表,工作表的标识和名称必须唯一。");
|
|
28
|
+
}
|
|
29
|
+
if (!directory.some(isWorkbookWorksheetVisible)) throw new Error("工作簿应至少保留一张可见工作表。");
|
|
30
|
+
for (const sheet of directory) {
|
|
31
|
+
validateWorkbookWorksheetName(sheet.name);
|
|
32
|
+
workbookWorksheetVisibility(sheet.visibility);
|
|
33
|
+
if (sheet.origin && original.has(sheet.id)) throw new Error("现有工作表不能替换其原始部件。");
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param node - Native directory entry. @param sheet - Committed worksheet state. */
|
|
38
|
+
export function writeXlsxWorksheetVisibility(node: Element, sheet: WorkbookWorksheetIdentity): void {
|
|
39
|
+
const visibility = sheet.visibility ?? "visible";
|
|
40
|
+
if ((node.getAttribute("state") || "visible") === visibility) return;
|
|
41
|
+
if (visibility === "visible") node.removeAttribute("state");
|
|
42
|
+
else node.setAttribute("state", visibility);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param workbook - Mutable native workbook root. @param source - Original package.
|
|
46
|
+
* @param parts - Mutable output parts. @param directory - Committed worksheet directory.
|
|
47
|
+
* @returns Native part paths keyed by current session IDs. */
|
|
48
|
+
export function writeWorksheetDirectory(
|
|
49
|
+
workbook: Element, source: XlsxPackage, parts: Record<string, Uint8Array>, directory: readonly WorkbookWorksheetIdentity[]
|
|
50
|
+
): ReadonlyMap<string, string> {
|
|
51
|
+
const before = source.baseline?.sheets;
|
|
52
|
+
if (!before || sameWorksheetDirectory(before, directory)) return source.sheetPaths;
|
|
53
|
+
const sheets = child(workbook, "sheets")!;
|
|
54
|
+
const original = new Map(children(sheets, "sheet").map(sheet => [sheet.getAttribute("sheetId") || sheet.getAttributeNS(relationshipNs, "id"), sheet]));
|
|
55
|
+
const formerlyVisible = new Set(before.filter(isWorkbookWorksheetVisible).map(({ id }) => id));
|
|
56
|
+
// A visibility edit lives in the directory and the affected views; the worksheet relationships retain their native identities.
|
|
57
|
+
if (sameWorksheetStructure(before, directory)) {
|
|
58
|
+
for (const sheet of directory) writeXlsxWorksheetVisibility(original.get(sheet.id)!, sheet);
|
|
59
|
+
updateXlsxWorkbookViews(workbook, before, directory);
|
|
60
|
+
clearHiddenSelections(parts, source.sheetPaths, directory, formerlyVisible);
|
|
61
|
+
return source.sheetPaths;
|
|
62
|
+
}
|
|
63
|
+
const paths = new Map(source.sheetPaths);
|
|
64
|
+
const relPath = relationshipsPath(source.workbookPath);
|
|
65
|
+
const relsXml = parsePart(parts[relPath], relPath);
|
|
66
|
+
const rels = rootOf(relsXml, packageRelationshipNs, "Relationships");
|
|
67
|
+
const typesPath = "[Content_Types].xml";
|
|
68
|
+
const typesXml = parsePart(parts[typesPath], typesPath);
|
|
69
|
+
const types = rootOf(typesXml, contentTypeNs, "Types");
|
|
70
|
+
const overrides = new Map(children(types, "Override").map(node => [node.getAttribute("PartName"), node]));
|
|
71
|
+
const relationships = new Map(children(rels, "Relationship").map(relation => [relation.getAttribute("Id"), relation]));
|
|
72
|
+
|
|
73
|
+
const live = new Set(directory.map(sheet => sheet.id));
|
|
74
|
+
const reservedIds = new Set([...original.values()].map(node => readIndex(node, "sheetId")));
|
|
75
|
+
const reservedPaths = new Set(Object.keys(parts).map(path => path.toLowerCase()));
|
|
76
|
+
const workbookDir = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
|
|
77
|
+
let sheetSerial = 1, relationshipSerial = 1, partSerial = 1;
|
|
78
|
+
// Preserve all three native identifiers on surviving sheets. Copies always have their own part.
|
|
79
|
+
for (const sheet of directory) {
|
|
80
|
+
let node = original.get(sheet.id);
|
|
81
|
+
if (!node) {
|
|
82
|
+
while (reservedIds.has(sheetSerial)) sheetSerial++;
|
|
83
|
+
while (relationships.has(`rId${relationshipSerial}`)) relationshipSerial++;
|
|
84
|
+
while (reservedPaths.has(`${workbookDir}worksheets/sheet${partSerial}.xml`.toLowerCase())) partSerial++;
|
|
85
|
+
const relationshipId = `rId${relationshipSerial++}`;
|
|
86
|
+
const target = `worksheets/sheet${partSerial++}.xml`;
|
|
87
|
+
const path = workbookDir + target;
|
|
88
|
+
node = workbook.ownerDocument!.createElementNS(spreadNs, "sheet");
|
|
89
|
+
node.setAttribute("sheetId", String(sheetSerial++));
|
|
90
|
+
node.setAttributeNS(relationshipNs, "r:id", relationshipId);
|
|
91
|
+
paths.set(sheet.id, path);
|
|
92
|
+
const originalId = sheet.origin?.sheetId;
|
|
93
|
+
const originalPath = originalId && source.sheetPaths.get(originalId);
|
|
94
|
+
parts[path] = originalId && originalPath
|
|
95
|
+
? copyWorksheetPart(parts[originalPath], originalPath, source.drawingGraphs?.has(originalId) === true,
|
|
96
|
+
source.hyperlinkRelations?.has(originalId) === true, source.commentGraph?.legacyDrawings.has(originalPath) === true)
|
|
97
|
+
: createXlsxWorksheetPart();
|
|
98
|
+
const relationship = relsXml.createElementNS(packageRelationshipNs, "Relationship");
|
|
99
|
+
relationship.setAttribute("Id", relationshipId);
|
|
100
|
+
relationship.setAttribute("Type", relationshipNs + "/worksheet");
|
|
101
|
+
relationship.setAttribute("Target", target);
|
|
102
|
+
rels.appendChild(relationship);
|
|
103
|
+
const override = typesXml.createElementNS(contentTypeNs, "Override");
|
|
104
|
+
override.setAttribute("PartName", "/" + path);
|
|
105
|
+
override.setAttribute("ContentType", "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
|
|
106
|
+
types.appendChild(override);
|
|
107
|
+
}
|
|
108
|
+
node.setAttribute("name", sheet.name);
|
|
109
|
+
writeXlsxWorksheetVisibility(node, sheet);
|
|
110
|
+
sheets.appendChild(node);
|
|
111
|
+
}
|
|
112
|
+
for (const [id, sheet] of original) {
|
|
113
|
+
if (!id || live.has(id)) continue;
|
|
114
|
+
const path = paths.get(id)!;
|
|
115
|
+
const relationship = relationships.get(sheet.getAttributeNS(relationshipNs, "id"));
|
|
116
|
+
const override = overrides.get("/" + path);
|
|
117
|
+
sheets.removeChild(sheet);
|
|
118
|
+
if (relationship) rels.removeChild(relationship);
|
|
119
|
+
if (override) types.removeChild(override);
|
|
120
|
+
delete parts[path];
|
|
121
|
+
delete parts[relationshipsPath(path)];
|
|
122
|
+
paths.delete(id);
|
|
123
|
+
}
|
|
124
|
+
parts[relPath] = writePart(relsXml);
|
|
125
|
+
parts[typesPath] = writePart(typesXml);
|
|
126
|
+
updateXlsxWorkbookViews(workbook, before, directory);
|
|
127
|
+
clearHiddenSelections(parts, paths, directory, formerlyVisible);
|
|
128
|
+
updatePrintNames(workbook, before, directory);
|
|
129
|
+
return paths;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @param parts - Output archive. @param paths - Committed native worksheets by stable ID.
|
|
133
|
+
* @param directory - Current worksheet directory. @param formerlyVisible - Original visible worksheet IDs. */
|
|
134
|
+
function clearHiddenSelections(parts: Record<string, Uint8Array>, paths: ReadonlyMap<string, string>,
|
|
135
|
+
directory: readonly WorkbookWorksheetIdentity[], formerlyVisible: ReadonlySet<string>): void {
|
|
136
|
+
for (const sheet of directory) {
|
|
137
|
+
const path = paths.get(sheet.id);
|
|
138
|
+
if (path && formerlyVisible.has(sheet.id) && !isWorkbookWorksheetVisible(sheet)) clearXlsxWorksheetTabSelection(parts, path);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** @param bytes - Original worksheet bytes. @param path - Original part path.
|
|
143
|
+
* @param managedDrawing - Whether the chart writer rebuilds this copy's drawings from its snapshot.
|
|
144
|
+
* @param managedLinks - Whether the codec regenerates the copy's native cell links.
|
|
145
|
+
* @param managedNotes - Whether the codec regenerates the copy's legacy comment drawing.
|
|
146
|
+
* @returns Independent worksheet part with its own view selection and relationships. */
|
|
147
|
+
function copyWorksheetPart(bytes: Uint8Array | undefined, path: string, managedDrawing: boolean, managedLinks: boolean, managedNotes: boolean): Uint8Array {
|
|
148
|
+
const document = parsePart(bytes, path);
|
|
149
|
+
const worksheet = rootOf(document, spreadNs, "worksheet");
|
|
150
|
+
const drawing = managedDrawing && child(worksheet, "drawing");
|
|
151
|
+
if (drawing) worksheet.removeChild(drawing);
|
|
152
|
+
const links = managedLinks && child(worksheet, "hyperlinks");
|
|
153
|
+
if (links) worksheet.removeChild(links);
|
|
154
|
+
const notes = managedNotes && child(worksheet, "legacyDrawing");
|
|
155
|
+
if (notes) worksheet.removeChild(notes);
|
|
156
|
+
// Background images are re-linked to the copied worksheet after its new part is installed.
|
|
157
|
+
const background = child(worksheet, "picture");
|
|
158
|
+
if (background) worksheet.removeChild(background);
|
|
159
|
+
const views = child(worksheet, "sheetViews");
|
|
160
|
+
if (views) for (const view of children(views, "sheetView")) view.removeAttribute("tabSelected");
|
|
161
|
+
return writePart(document);
|
|
162
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { projectWorkbookAppearance, retainWorkbookFormulaResults, sameWorkbookConditionalFormats, sameWorkbookPrintLayout,
|
|
2
|
+
sameWorkbookValidations, workbookPositionEdits, workbookProgressRules, type WorkbookFormulaSpill, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
3
|
+
import { zipSync } from "fflate";
|
|
4
|
+
import { writeWorkbookComments } from "../comments/package/write";
|
|
5
|
+
import { writeWorkbookDrawings } from "../drawing/write/workbook";
|
|
6
|
+
import { xlsxExternalFormulaCheck, xlsxExternalLinksChanged } from "../external-links/formulas";
|
|
7
|
+
import { writeXlsxExternalLinks } from "../external-links/write";
|
|
8
|
+
import { writeWorkbookCellImages } from "../image/write";
|
|
9
|
+
import { removeXlsxArrayMetadataPart, writeXlsxArrayMetadataPart } from "../metadata/package";
|
|
10
|
+
import { relationshipsPath } from "../opc/relationships";
|
|
11
|
+
import { child, children, contentTypeNs, packageRelationshipNs, parsePart, rootOf, spreadNs, writePart } from "../opc/xml";
|
|
12
|
+
import { writeWorkbookPivots } from "../pivot/package/write";
|
|
13
|
+
import type { XlsxDifferentialStyle } from "../styles/types";
|
|
14
|
+
import { createXlsxStyleWriter } from "../styles/write";
|
|
15
|
+
import { removeXlsxStructuredTables } from "../table/remove";
|
|
16
|
+
import { writeWorkbookStructuredTables, xlsxTableFiltersBySheet } from "../table/write";
|
|
17
|
+
import type { XlsxWriteOptions } from "../types";
|
|
18
|
+
import { writeWorkbookNamedViews } from "../worksheet/view/named/write";
|
|
19
|
+
import { writeWorkbookBackgrounds } from "../worksheet/background/write";
|
|
20
|
+
import { xlsxNamedHyperlinkLocations } from "../worksheet/hyperlinks/location";
|
|
21
|
+
import { ensurePrimaryWorkbookView, sameXlsxWorksheetView } from "../worksheet/view/write";
|
|
22
|
+
import { writeXlsxCalculationSettings } from "./calculation-metadata";
|
|
23
|
+
import { registerXlsxCheckboxes } from "./checkboxes";
|
|
24
|
+
import { sameXlsxDashboards, writeXlsxDashboards } from "./dashboard";
|
|
25
|
+
import { sameXlsxMergeRecipes, writeXlsxMergeRecipes } from "./merge-recipes";
|
|
26
|
+
import { writeWorkbookDefinedNames } from "./names/defined";
|
|
27
|
+
import { writeFilterDatabaseNames } from "./names/filter";
|
|
28
|
+
import { writeXlsxPrintRanges } from "./names/print-layout";
|
|
29
|
+
import { writeXlsxWorksheetParts } from "./save/worksheets";
|
|
30
|
+
import { registerXlsxStyles } from "./styles";
|
|
31
|
+
import type { XlsxPackage } from "./types";
|
|
32
|
+
import { sameWorksheetDirectory, writeWorksheetDirectory } from "./worksheets";
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param source - Read or newly created package.
|
|
36
|
+
* @param snapshot - Committed workbook.
|
|
37
|
+
* @param writeOptions - Optional calculated value source.
|
|
38
|
+
* @param writeInputs - Also write cell inputs and refresh calculation caches.
|
|
39
|
+
* @returns XLSX package with cell data and consistent dependencies.
|
|
40
|
+
*/
|
|
41
|
+
export function writeXlsxPackage(
|
|
42
|
+
source: XlsxPackage, snapshot: WorkbookSnapshot, writeOptions: XlsxWriteOptions = {}, writeInputs = true
|
|
43
|
+
): Uint8Array {
|
|
44
|
+
const retained = retainWorkbookFormulaResults(snapshot);
|
|
45
|
+
const options: XlsxWriteOptions = retained ? {
|
|
46
|
+
...writeOptions,
|
|
47
|
+
/** @param address - Cell written to the native package. @returns Its published result, or the host's ordinary value reader. */
|
|
48
|
+
result: address => retained.read(address) ?? writeOptions.result?.(address) ?? { status: "unavailable" }
|
|
49
|
+
} : writeOptions;
|
|
50
|
+
const oldArrays = spillSheets(source.baseline?.formulaResults?.flatMap(entry => entry.spill ? [entry.spill] : []) ?? []);
|
|
51
|
+
const newArrays = spillSheets(retained?.spills.entries ?? []);
|
|
52
|
+
const parts = { ...source.parts };
|
|
53
|
+
const supportsExternalFormula = xlsxExternalFormulaCheck(snapshot.externalLinks);
|
|
54
|
+
removeXlsxStructuredTables(source, parts, snapshot);
|
|
55
|
+
const originals = new Map(source.baseline?.sheets.map(sheet => [sheet.id, sheet]));
|
|
56
|
+
const priorTableFilters = xlsxTableFiltersBySheet(source.baseline?.structuredTables);
|
|
57
|
+
const tableFilters = xlsxTableFiltersBySheet(snapshot.structuredTables ?? source.baseline?.structuredTables);
|
|
58
|
+
const names = new Map(snapshot.sheets.map(sheet => [sheet.id, sheet.name]));
|
|
59
|
+
const namedLocations = xlsxNamedHyperlinkLocations(snapshot.definedNames, names);
|
|
60
|
+
const oldLocations = xlsxNamedHyperlinkLocations(source.baseline?.definedNames, new Map(source.baseline?.sheets.map(({ id, name }) => [id, name])));
|
|
61
|
+
const renamedSheets = new Set(snapshot.sheets.filter(sheet => originals.has(sheet.id) && originals.get(sheet.id)?.name !== sheet.name)
|
|
62
|
+
.map(sheet => sheet.id));
|
|
63
|
+
const positions = source.baseline ? workbookPositionEdits(snapshot) : [];
|
|
64
|
+
const appearance = projectWorkbookAppearance(source.appearance, positions, snapshot.sheets);
|
|
65
|
+
const viewsChanged = snapshot.sheets.some(sheet => !sameXlsxWorksheetView(originals.get(sheet.origin?.sheetId ?? sheet.id)?.view, sheet.view));
|
|
66
|
+
const printChanges = new Set(snapshot.sheets.filter(sheet => !sameWorkbookPrintLayout(
|
|
67
|
+
originals.get(sheet.origin?.sheetId ?? sheet.id)?.view?.printLayout, sheet.view?.printLayout)).map(sheet => sheet.id));
|
|
68
|
+
const directoryChanged = source.baseline && !sameWorksheetDirectory(source.baseline.sheets, snapshot.sheets);
|
|
69
|
+
const dashboardsChanged = !sameXlsxDashboards(source.baseline?.sheets, snapshot.sheets);
|
|
70
|
+
const workbookXml = writeInputs || viewsChanged || directoryChanged || printChanges.size || dashboardsChanged
|
|
71
|
+
? parsePart(writePart(source.workbookXml), source.workbookPath) : undefined;
|
|
72
|
+
const workbook = workbookXml && rootOf(workbookXml, spreadNs, "workbook");
|
|
73
|
+
const paths = directoryChanged && workbook ? writeWorksheetDirectory(workbook, source, parts, snapshot.sheets) : source.sheetPaths;
|
|
74
|
+
const progress = new Map(snapshot.sheets.map(sheet => [sheet.id, workbookProgressRules(sheet.validations)]));
|
|
75
|
+
const ruleChanges = new Set(snapshot.sheets.filter(sheet => {
|
|
76
|
+
const original = originals.get(sheet.origin?.sheetId ?? sheet.id);
|
|
77
|
+
return !sameWorkbookConditionalFormats(original?.conditionalFormats, sheet.conditionalFormats)
|
|
78
|
+
|| !sameWorkbookValidations(workbookProgressRules(original?.validations), progress.get(sheet.id));
|
|
79
|
+
}).map(sheet => sheet.id));
|
|
80
|
+
const hasCheckboxes = snapshot.sheets.some(sheet => sheet.checkboxes?.length);
|
|
81
|
+
const tableSortColors = (snapshot.structuredTables ?? source.baseline?.structuredTables)?.some(table =>
|
|
82
|
+
Object.values(table.sorts ?? {}).some(state => state?.keys.some(key => "source" in key)));
|
|
83
|
+
const stylePath = hasCheckboxes || source.checkboxStyles || tableSortColors || snapshot.sheets.some(sheet => sheet.formats?.length
|
|
84
|
+
|| [sheet.autoFilter, ...(tableFilters.get(sheet.id) ?? [])].some(filter => filter?.columns.some(({ rule }) => rule.kind === "color"))
|
|
85
|
+
|| Object.values(sheet.sorts ?? {}).some(state => state?.keys.some(key => "source" in key))
|
|
86
|
+
|| ((sheet.conditionalFormats?.length || progress.get(sheet.id)?.length) && ruleChanges.has(sheet.id)))
|
|
87
|
+
? registerXlsxStyles(source, parts) : undefined;
|
|
88
|
+
const complement = hasCheckboxes ? registerXlsxCheckboxes(source, parts) : undefined;
|
|
89
|
+
const styles = stylePath ? createXlsxStyleWriter(parts[stylePath], stylePath, complement) : undefined;
|
|
90
|
+
/** @param style - Color used by a native data criterion. @returns The differential style index in the styles part. */
|
|
91
|
+
function addFilterStyle(style: XlsxDifferentialStyle): number {
|
|
92
|
+
if (!styles) throw new Error("颜色条件缺少差异样式表。");
|
|
93
|
+
return styles.addDifferential(style);
|
|
94
|
+
}
|
|
95
|
+
if (writeInputs) removeXlsxArrayMetadataPart(parts, source.workbookPath, source.arrayMetadata);
|
|
96
|
+
const imageIndex = writeInputs ? writeWorkbookCellImages(source, parts, snapshot) : undefined;
|
|
97
|
+
if (writeInputs && newArrays.size) writeXlsxArrayMetadataPart(parts, source.workbookPath);
|
|
98
|
+
|
|
99
|
+
// Sheet parts claim their shared style indices first. The drawing and workbook-level parts then follow final sheet positions.
|
|
100
|
+
const revisedDrawingLayout = writeXlsxWorksheetParts(source, parts, snapshot.sheets, { options, writeInputs, paths, originals, positions,
|
|
101
|
+
appearance, printChanges, ruleChanges, progress, oldArrays, newArrays, priorTableFilters, tableFilters, names,
|
|
102
|
+
namedLocations, oldLocations, renamedSheets, supportsExternalFormula, styles, imageIndex, retainedResultsAt, addFilterStyle });
|
|
103
|
+
writeWorkbookDrawings(source, parts, paths, snapshot, options, writeInputs, revisedDrawingLayout);
|
|
104
|
+
writeWorkbookBackgrounds(source, parts, paths, snapshot);
|
|
105
|
+
writeWorkbookComments(source, parts, snapshot, paths);
|
|
106
|
+
const tableSerials = writeWorkbookStructuredTables(source, parts, snapshot, paths, addFilterStyle);
|
|
107
|
+
writeWorkbookNamedViews(source, parts, paths, snapshot, tableSerials);
|
|
108
|
+
if (styles && stylePath) parts[stylePath] = writePart(styles.document);
|
|
109
|
+
if (!workbookXml || !workbook) return zipSync(parts, { level: 3 });
|
|
110
|
+
const addedView = viewsChanged && ensurePrimaryWorkbookView(workbook);
|
|
111
|
+
const mergeRecipesChanged = !sameXlsxMergeRecipes(source.baseline?.tableMergeRecipes, snapshot.tableMergeRecipes);
|
|
112
|
+
if (mergeRecipesChanged) writeXlsxMergeRecipes(workbook, snapshot.sheets, snapshot.tableMergeRecipes ?? []);
|
|
113
|
+
if (dashboardsChanged) writeXlsxDashboards(workbook, snapshot.sheets);
|
|
114
|
+
for (const [index, sheet] of snapshot.sheets.entries()) {
|
|
115
|
+
if (printChanges.has(sheet.id)) writeXlsxPrintRanges(workbook, sheet, index, originals.get(sheet.origin?.sheetId ?? sheet.id));
|
|
116
|
+
}
|
|
117
|
+
if (!writeInputs) {
|
|
118
|
+
if (addedView || directoryChanged || printChanges.size || mergeRecipesChanged || dashboardsChanged) parts[source.workbookPath] = writePart(workbookXml);
|
|
119
|
+
return zipSync(parts, { level: 3 });
|
|
120
|
+
}
|
|
121
|
+
if (xlsxExternalLinksChanged(source.baseline?.externalLinks, snapshot.externalLinks)) writeXlsxExternalLinks(source, parts, workbook, snapshot.externalLinks);
|
|
122
|
+
writeFilterDatabaseNames(workbook, snapshot.sheets);
|
|
123
|
+
writeWorkbookDefinedNames(workbook, snapshot.definedNames ?? [], snapshot.sheets);
|
|
124
|
+
writeWorkbookPivots(source, parts, workbook, snapshot, paths);
|
|
125
|
+
|
|
126
|
+
// A retained round has authoritative native caches. Other changes request a fresh calculation after open.
|
|
127
|
+
const existing = child(workbook, "calcPr");
|
|
128
|
+
const settings = existing ?? workbookXml.createElementNS(spreadNs, "calcPr");
|
|
129
|
+
const manual = snapshot.calculationSettings?.mode === "manual";
|
|
130
|
+
settings.setAttribute("fullCalcOnLoad", retained || manual ? "0" : "1");
|
|
131
|
+
if (retained || manual) {
|
|
132
|
+
settings.setAttribute("calcCompleted", manual && (snapshot.formulaPendingRevision !== undefined || !retained) ? "0" : "1");
|
|
133
|
+
if (settings.hasAttribute("forceFullCalc")) settings.setAttribute("forceFullCalc", "0");
|
|
134
|
+
}
|
|
135
|
+
writeXlsxCalculationSettings(settings, snapshot.calculationSettings, source.baseline?.calculationSettings);
|
|
136
|
+
if (!existing) {
|
|
137
|
+
const after = children(workbook).find(node => ["oleSize", "customWorkbookViews", "pivotCaches", "smartTagPr", "smartTagTypes", "webPublishing", "fileRecoveryPr", "webPublishObjects", "extLst"].includes(node.localName ?? ""));
|
|
138
|
+
workbook.insertBefore(settings, after ?? null);
|
|
139
|
+
}
|
|
140
|
+
parts[source.workbookPath] = writePart(workbookXml);
|
|
141
|
+
const staleChains = [...source.relationships.values()].filter(relation => relation.type.endsWith("/calcChain"));
|
|
142
|
+
if (staleChains.length > 0) {
|
|
143
|
+
const relPath = relationshipsPath(source.workbookPath);
|
|
144
|
+
const rels = parsePart(parts[relPath], relPath);
|
|
145
|
+
const types = parsePart(parts["[Content_Types].xml"], "[Content_Types].xml");
|
|
146
|
+
const content = rootOf(types, contentTypeNs, "Types");
|
|
147
|
+
const paths = new Set(staleChains.map(chain => chain.path));
|
|
148
|
+
const ids = new Set(staleChains.map(chain => chain.id));
|
|
149
|
+
for (const path of paths) if (path !== null) delete parts[path];
|
|
150
|
+
const relRoot = rootOf(rels, packageRelationshipNs, "Relationships");
|
|
151
|
+
for (const relation of children(relRoot)) if (ids.has(relation.getAttribute("Id") ?? "")) relRoot.removeChild(relation);
|
|
152
|
+
for (const node of children(content, "Override")) {
|
|
153
|
+
if (paths.has((node.getAttribute("PartName") ?? "").replace(/^\//u, ""))) content.removeChild(node);
|
|
154
|
+
}
|
|
155
|
+
parts[relPath] = writePart(rels);
|
|
156
|
+
parts["[Content_Types].xml"] = writePart(types);
|
|
157
|
+
}
|
|
158
|
+
return zipSync(parts, { level: 3 });
|
|
159
|
+
|
|
160
|
+
/** @param sheetId - Target sheet. @returns Current array lookup when its result cells need to be written. */
|
|
161
|
+
function retainedResultsAt(sheetId: string) {
|
|
162
|
+
return writeInputs && newArrays.has(sheetId) ? retained?.spills.at : undefined;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** @param entries - Authored formula outputs. @returns The source or destination arrays grouped by sheet. */
|
|
167
|
+
function spillSheets(entries: readonly WorkbookFormulaSpill[]) {
|
|
168
|
+
const grouped = new Map<string, WorkbookFormulaSpill[]>();
|
|
169
|
+
for (const entry of entries) {
|
|
170
|
+
const values = grouped.get(entry.range.sheetId) ?? [];
|
|
171
|
+
values.push(entry);
|
|
172
|
+
grouped.set(entry.range.sheetId, values);
|
|
173
|
+
}
|
|
174
|
+
return grouped;
|
|
175
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { maximumWorkbookPivotCalculatedFields, type WorkbookPivotCalculatedField } from "@quirekit/workbook";
|
|
3
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
4
|
+
import { child } from "../../opc/xml";
|
|
5
|
+
import { decodeXlsxText, encodeXlsxText } from "../../worksheet/text";
|
|
6
|
+
import { pivotChild } from "../xml";
|
|
7
|
+
|
|
8
|
+
/** @param fields - Cache fields in native order. @param names - Decoded field captions.
|
|
9
|
+
* @param width - Source table width. @returns Calculated definitions indexed by the native field. */
|
|
10
|
+
export function readXlsxPivotCalculatedFields(fields: readonly Element[], names: readonly string[],
|
|
11
|
+
width: number): ReadonlyMap<number, WorkbookPivotCalculatedField> {
|
|
12
|
+
const calculated = new Map<number, WorkbookPivotCalculatedField>();
|
|
13
|
+
fields.forEach((field, index) => {
|
|
14
|
+
if (!field.hasAttribute("formula")) return;
|
|
15
|
+
const formula = decodeXlsxText(field.getAttribute("formula") ?? "").trim();
|
|
16
|
+
const shared = child(field, "sharedItems");
|
|
17
|
+
if (index < width || !formula || !["0", "false"].includes(field.getAttribute("databaseField") ?? "")
|
|
18
|
+
|| !["0", ""].includes(field.getAttribute("numFmtId") ?? "")
|
|
19
|
+
|| !hasKnownAttributes(field, ["name", "numFmtId", "formula", "databaseField"])
|
|
20
|
+
|| !hasKnownChildren(field, ["sharedItems"]) || shared && (!hasKnownAttributes(shared, ["count"])
|
|
21
|
+
|| !["0", ""].includes(shared.getAttribute("count") ?? "") || !hasKnownChildren(shared, []))) {
|
|
22
|
+
throw new Error("数据透视表含未支持的计算字段定义。");
|
|
23
|
+
}
|
|
24
|
+
calculated.set(index, { name: names[index]!, formula: formula.startsWith("=") ? formula : "=" + formula });
|
|
25
|
+
});
|
|
26
|
+
if (calculated.size > maximumWorkbookPivotCalculatedFields) throw new Error("数据透视表的计算字段数量超出上限。");
|
|
27
|
+
return calculated;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @param parent - Cache field list. @param field - Validated calculated definition. */
|
|
31
|
+
export function writeXlsxPivotCalculatedField(parent: Element, { name, formula }: WorkbookPivotCalculatedField): void {
|
|
32
|
+
pivotChild(parent, "cacheField", { name: encodeXlsxText(name), numFmtId: 0,
|
|
33
|
+
formula: encodeXlsxText(formula.slice(1)), databaseField: false });
|
|
34
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookClockTime, formatWorkbookDate, maximumWorkbookPivotCells, maximumWorkbookPivotDayInterval, workbookDateTimeSeconds,
|
|
3
|
+
workbookPivotDateItemCount, workbookPivotDateUnits, workbookPivotKey, workbookPivotTimeUnits,
|
|
4
|
+
type WorkbookPivotCache, type WorkbookPivotResolvedDateField, type WorkbookSession } from "@quirekit/workbook";
|
|
5
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
6
|
+
import { child, children, readIndex } from "../../opc/xml";
|
|
7
|
+
import { readXlsxDateSerial, writeXlsxDateSerial } from "../../value/date";
|
|
8
|
+
import type { XlsxPivotDateField } from "../types";
|
|
9
|
+
import { pivotChild } from "../xml";
|
|
10
|
+
import { readPivotRangeAutomatic } from "./groups";
|
|
11
|
+
import { readXlsxPivotTime, writeXlsxPivotTime } from "./time";
|
|
12
|
+
import { readPivotValue, writePivotValue } from "./values";
|
|
13
|
+
|
|
14
|
+
/** @param field - Original cache field. @param index - Native index.
|
|
15
|
+
* @param cache - Typed source rows. @param name - Decoded field name. @param dateSystem - Workbook epoch.
|
|
16
|
+
* @returns The native date or clock grouping, if one exists. */
|
|
17
|
+
export function readXlsxPivotDateField(field: Element, index: number, cache: WorkbookPivotCache, name: string,
|
|
18
|
+
dateSystem: WorkbookSession["dateSystem"]): XlsxPivotDateField | undefined {
|
|
19
|
+
const group = child(field, "fieldGroup");
|
|
20
|
+
if (!group) return undefined;
|
|
21
|
+
const sourceField = readIndex(group, "base");
|
|
22
|
+
const parent = readIndex(group, "par");
|
|
23
|
+
const range = child(group, "rangePr"), values = child(group, "groupItems");
|
|
24
|
+
const unit = workbookPivotDateUnits.find(value => value === range?.getAttribute("groupBy"));
|
|
25
|
+
const clock = sourceField !== undefined && cache.timeFields?.includes(sourceField) === true;
|
|
26
|
+
const interval = range?.hasAttribute("groupInterval") ? Number(range.getAttribute("groupInterval")) : 1;
|
|
27
|
+
if (sourceField === undefined || !clock && !cache.dateFields?.includes(sourceField) || !unit || !range || !values
|
|
28
|
+
|| clock && !workbookPivotTimeUnits.some(time => time === unit)
|
|
29
|
+
|| index < cache.fields.length && sourceField !== index || group.hasAttribute("par") && parent === undefined
|
|
30
|
+
|| !hasKnownChildren(group, ["rangePr", "groupItems"]) || !hasKnownAttributes(group, ["base", "par"])
|
|
31
|
+
|| !hasKnownChildren(range, []) || !hasKnownAttributes(range, ["groupBy", "startDate", "endDate", "autoStart", "autoEnd", "groupInterval"])
|
|
32
|
+
|| !Number.isInteger(interval) || interval < 1 || interval > maximumWorkbookPivotDayInterval
|
|
33
|
+
|| interval > 1 && unit !== "days" || !hasKnownAttributes(values, ["count"])) {
|
|
34
|
+
throw new Error("数据透视表使用了未映射的日期分组。");
|
|
35
|
+
}
|
|
36
|
+
const autoStart = readPivotRangeAutomatic(range, "autoStart"), autoEnd = readPivotRangeAutomatic(range, "autoEnd");
|
|
37
|
+
let first = Infinity, last = -Infinity;
|
|
38
|
+
for (const record of cache.records) {
|
|
39
|
+
const value = record[sourceField] as number;
|
|
40
|
+
const point = clock ? value : Math.floor(value);
|
|
41
|
+
first = Math.min(first, point);
|
|
42
|
+
last = Math.max(last, point);
|
|
43
|
+
}
|
|
44
|
+
const read = clock ? readClockBound : readBound;
|
|
45
|
+
const lower = read(range, "startDate", autoStart, first, dateSystem);
|
|
46
|
+
const upper = read(range, "endDate", autoEnd, last, dateSystem);
|
|
47
|
+
const startDay = Math.floor(lower.serial), endDay = Math.floor(upper.serial);
|
|
48
|
+
// Earlier workbook exports used midnight to represent an entire end date for coarse periods.
|
|
49
|
+
const legacyMidnight = ["years", "quarters", "months"].includes(unit) && upper.text?.endsWith("T00:00:00");
|
|
50
|
+
const wholeEndDay = clock || autoEnd || legacyMidnight || upper.text === nativeWholeDayEnd(endDay, dateSystem);
|
|
51
|
+
const startTimestamp = !clock && !autoStart && lower.serial !== startDay ? lower.text : undefined;
|
|
52
|
+
const endTimestamp = !wholeEndDay && upper.text?.includes("T") ? upper.text.replace(/(T00:00:00)\.0+$/u, "$1") : undefined;
|
|
53
|
+
const start = lower.serial, end = clock || endTimestamp ? upper.serial : endDay;
|
|
54
|
+
const members = children(values);
|
|
55
|
+
const firstLabel = clock ? formatWorkbookClockTime(start) : formatWorkbookDate(startDay, dateSystem);
|
|
56
|
+
const lastLabel = clock ? formatWorkbookClockTime(end) : formatWorkbookDate(endDay, dateSystem);
|
|
57
|
+
const count = workbookPivotDateItemCount(unit, firstLabel, lastLabel, interval, dateSystem);
|
|
58
|
+
const reversed = clock ? workbookDateTimeSeconds(start) > workbookDateTimeSeconds(end) : endTimestamp ? start > end : startDay > endDay;
|
|
59
|
+
if (reversed || count > maximumWorkbookPivotCells || members.length !== count
|
|
60
|
+
|| values.hasAttribute("count") && readIndex(values, "count") !== members.length) {
|
|
61
|
+
throw new Error("数据透视表的日期分组成员与边界不一致。");
|
|
62
|
+
}
|
|
63
|
+
const items = members.map(member => {
|
|
64
|
+
const value = readPivotValue(member);
|
|
65
|
+
if (typeof value !== "string" && typeof value !== "number") throw new Error("数据透视表使用了未映射的日期组标签。");
|
|
66
|
+
return value;
|
|
67
|
+
});
|
|
68
|
+
if (new Set(items.map(workbookPivotKey)).size !== items.length) throw new Error("数据透视表的日期组标签不唯一。");
|
|
69
|
+
return { field: index, sourceField, unit, name, parent, start, end, autoStart, autoEnd, items,
|
|
70
|
+
startTimestamp, endTimestamp, ...(clock && { clock: true }), ...(interval > 1 && { daysPerGroup: interval }) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** @param range - Native grouping range. @param key - Lower or upper date attribute.
|
|
74
|
+
* @param automatic - Whether the original producer follows its source. @param inferred - Bound from the original cache.
|
|
75
|
+
* @param system - Epoch declared by the workbook. @returns The native boundary and exact local spelling, when present. */
|
|
76
|
+
function readBound(range: Element, key: "startDate" | "endDate", automatic: boolean, inferred: number, system: "1900" | "1904") {
|
|
77
|
+
if (!range.hasAttribute(key) && automatic) return { serial: inferred, text: undefined };
|
|
78
|
+
const text = (range.getAttribute(key) ?? "").replace(/Z$/u, "");
|
|
79
|
+
const serial = readXlsxDateSerial(text, system);
|
|
80
|
+
if (serial === undefined || serial < (system === "1900" ? 1 : 0) || automatic && Math.floor(serial) !== inferred) {
|
|
81
|
+
throw new Error("数据透视表使用了未映射的日期分组边界。");
|
|
82
|
+
}
|
|
83
|
+
return { serial: automatic ? inferred : serial, text };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** @param range - Native grouping range. @param key - Lower or upper date attribute.
|
|
87
|
+
* @param automatic - Whether this end follows the source. @param inferred - Bound from the cached records.
|
|
88
|
+
* @param system - Epoch declared by the workbook. @returns The exact clock serial to use for this end. */
|
|
89
|
+
function readClockBound(range: Element, key: "startDate" | "endDate", automatic: boolean, inferred: number, system: WorkbookSession["dateSystem"]) {
|
|
90
|
+
if (!range.hasAttribute(key) && automatic) return { serial: inferred, text: undefined };
|
|
91
|
+
const serial = readXlsxPivotTime(range.getAttribute(key) ?? "", system);
|
|
92
|
+
// WPS may store a 1904 automatic range with midnight in the XML, even when the result contains later times.
|
|
93
|
+
const placeholder = system === "1904" && serial === 0;
|
|
94
|
+
if (serial === undefined || automatic && !placeholder && workbookDateTimeSeconds(serial) !== workbookDateTimeSeconds(inferred)) {
|
|
95
|
+
throw new Error("数据透视表使用了未映射的时间分组边界。");
|
|
96
|
+
}
|
|
97
|
+
return { serial: automatic ? inferred : serial, text: undefined };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** @param field - Native cache field. @param level - Planned range and member indexes. @param system - Workbook epoch.
|
|
101
|
+
* @returns The indexes that this pivot definition will use for the field. */
|
|
102
|
+
export function writeXlsxPivotDateField(field: Element, level: WorkbookPivotResolvedDateField,
|
|
103
|
+
system: "1900" | "1904"): ReadonlyMap<string, number> {
|
|
104
|
+
const group = pivotChild(field, "fieldGroup", { base: level.sourceField });
|
|
105
|
+
// Keep an explicitly selected midnight distinguishable from the legacy whole-day encoding.
|
|
106
|
+
const timestamp = level.endTimestamp?.endsWith("T00:00:00") ? level.endTimestamp + ".0" : level.endTimestamp;
|
|
107
|
+
pivotChild(group, "rangePr", { groupBy: level.unit, autoStart: level.autoStart ? undefined : false,
|
|
108
|
+
autoEnd: level.autoEnd ? undefined : false,
|
|
109
|
+
startDate: level.clock ? writeXlsxPivotTime(level.start, system) : level.startTimestamp ?? writeXlsxDateSerial(level.start, system),
|
|
110
|
+
endDate: level.clock ? writeXlsxPivotTime(level.end, system)
|
|
111
|
+
: timestamp ?? (level.autoEnd ? writeXlsxDateSerial(level.end, system) : nativeWholeDayEnd(level.end, system)),
|
|
112
|
+
groupInterval: level.daysPerGroup ?? 1 });
|
|
113
|
+
const items = pivotChild(group, "groupItems", { count: level.items.length });
|
|
114
|
+
level.items.forEach(value => writePivotValue(items, value));
|
|
115
|
+
return new Map(level.items.map((value, index) => [workbookPivotKey(value), index]));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** @param day - Inclusive final day in the workbook epoch. @param system - Workbook calendar.
|
|
119
|
+
* @returns The final representable instant before midnight for a native inclusive end bound. */
|
|
120
|
+
function nativeWholeDayEnd(day: number, system: "1900" | "1904"): string {
|
|
121
|
+
const nextDay = day + 1;
|
|
122
|
+
const spacing = 2 ** (Math.ceil(Math.log2(nextDay)) - 53);
|
|
123
|
+
return writeXlsxDateSerial(nextDay - spacing, system);
|
|
124
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { isTrue } from "../../opc/xml";
|
|
3
|
+
|
|
4
|
+
/** @param range - Native grouping range. @param key - Automatic lower or upper flag.
|
|
5
|
+
* @returns True for a bound inferred from the cache, including the native default. */
|
|
6
|
+
export function readPivotRangeAutomatic(range: Element, key: "autoStart" | "autoEnd"): boolean {
|
|
7
|
+
const value = range.getAttribute(key);
|
|
8
|
+
if (!range.hasAttribute(key)) return true;
|
|
9
|
+
if (!["0", "1", "false", "true"].includes(value ?? "")) throw new Error("数据透视表使用了无效的自动分组边界。");
|
|
10
|
+
return isTrue(value);
|
|
11
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { maximumWorkbookPivotCells, workbookPivotKey, type WorkbookPivotCache, type WorkbookPivotResolvedMemberField,
|
|
3
|
+
type WorkbookPivotValue } from "@quirekit/workbook";
|
|
4
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
5
|
+
import { child, children, readIndex } from "../../opc/xml";
|
|
6
|
+
import { pivotChild, pivotMembers } from "../xml";
|
|
7
|
+
import { readPivotValue, writePivotValue } from "./values";
|
|
8
|
+
|
|
9
|
+
/** @param fields - Native cache fields. @param names - Decoded cache field names. @param shared - Raw shared items.
|
|
10
|
+
* @param cache - Source field count and calendar. @returns Validated discrete groups in native field order. */
|
|
11
|
+
export function readXlsxPivotMemberFields(fields: readonly Element[], names: readonly string[],
|
|
12
|
+
shared: readonly (readonly WorkbookPivotValue[])[], cache: WorkbookPivotCache): ReadonlyMap<number, WorkbookPivotResolvedMemberField> {
|
|
13
|
+
const result = new Map<number, WorkbookPivotResolvedMemberField>();
|
|
14
|
+
const sources = new Set<number>();
|
|
15
|
+
let remaining = maximumWorkbookPivotCells;
|
|
16
|
+
for (const [field, node] of fields.entries()) {
|
|
17
|
+
const group = child(node, "fieldGroup");
|
|
18
|
+
const discrete = group && child(group, "discretePr");
|
|
19
|
+
if (!group || !discrete) continue;
|
|
20
|
+
const base = readIndex(group, "base");
|
|
21
|
+
const parent = readIndex(group, "par");
|
|
22
|
+
const itemsNode = child(group, "groupItems");
|
|
23
|
+
if (field < cache.fields.length || base === undefined || base >= cache.fields.length
|
|
24
|
+
|| group.hasAttribute("par") && parent === undefined
|
|
25
|
+
|| !hasKnownAttributes(group, ["base", "par"]) || !hasKnownChildren(group, ["discretePr", "groupItems"])
|
|
26
|
+
|| !hasKnownAttributes(discrete, ["count"]) || !itemsNode || !hasKnownAttributes(itemsNode, ["count"])) {
|
|
27
|
+
throw new Error("数据透视表包含未映射的手工分组结构。");
|
|
28
|
+
}
|
|
29
|
+
const sourceItems = shared[base]!;
|
|
30
|
+
const entries = pivotMembers(discrete, "x");
|
|
31
|
+
const childrenOfItems = children(itemsNode);
|
|
32
|
+
remaining -= sourceItems.length;
|
|
33
|
+
if (remaining < 0 || entries.length !== sourceItems.length || !childrenOfItems.length
|
|
34
|
+
|| childrenOfItems.length > sourceItems.length
|
|
35
|
+
|| itemsNode.hasAttribute("count") && readIndex(itemsNode, "count") !== childrenOfItems.length) {
|
|
36
|
+
throw new Error("自定义分组无法映射到其原始字段成员。");
|
|
37
|
+
}
|
|
38
|
+
const items = childrenOfItems.map(item => readPivotValue(item, cache.dateSystem));
|
|
39
|
+
const mapping = entries.map(entry => {
|
|
40
|
+
const ordinal = readIndex(entry, "v");
|
|
41
|
+
if (ordinal === undefined || ordinal >= items.length || !hasKnownAttributes(entry, ["v"]) || !hasKnownChildren(entry, [])) {
|
|
42
|
+
throw new Error("自定义分组引用了不存在的成员。");
|
|
43
|
+
}
|
|
44
|
+
return ordinal;
|
|
45
|
+
});
|
|
46
|
+
if (new Set(mapping).size !== items.length || new Set(items.map(workbookPivotKey)).size !== items.length) {
|
|
47
|
+
throw new Error("自定义分组的缓存成员未形成唯一映射。");
|
|
48
|
+
}
|
|
49
|
+
sources.add(base);
|
|
50
|
+
result.set(field, { field, sourceField: base, memberLevel: 0, parent, name: names[field]!, sourceItems, mapping, items });
|
|
51
|
+
}
|
|
52
|
+
// Native field indexes need not be in level order. Follow the real field's parent links.
|
|
53
|
+
for (const base of sources) {
|
|
54
|
+
const root = child(fields[base]!, "fieldGroup");
|
|
55
|
+
if (!root || root.hasAttribute("base") && readIndex(root, "base") !== base
|
|
56
|
+
|| !hasKnownAttributes(root, ["par", "base"]) || !hasKnownChildren(root, [])) {
|
|
57
|
+
throw new Error("数据透视表包含未映射的手工分组来源。");
|
|
58
|
+
}
|
|
59
|
+
let index = readIndex(root, "par");
|
|
60
|
+
let prior: WorkbookPivotResolvedMemberField | undefined;
|
|
61
|
+
while (index !== undefined) {
|
|
62
|
+
const level = result.get(index);
|
|
63
|
+
if (!level || level.sourceField !== base || level.memberLevel > 0) {
|
|
64
|
+
throw new Error("数据透视表包含无效的多层手工分组链接。");
|
|
65
|
+
}
|
|
66
|
+
if (prior) verifyXlsxPivotMemberParent(prior, level);
|
|
67
|
+
result.set(index, { ...level, memberLevel: (prior?.memberLevel ?? 0) + 1 });
|
|
68
|
+
prior = result.get(index);
|
|
69
|
+
index = level.parent;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if ([...result.values()].some(level => !level.memberLevel)) {
|
|
73
|
+
throw new Error("数据透视表包含未连接的手工分组字段。");
|
|
74
|
+
}
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** @param child - Level closer to the source. @param parent - The next outer level over the same raw items. */
|
|
79
|
+
function verifyXlsxPivotMemberParent(child: WorkbookPivotResolvedMemberField, parent: WorkbookPivotResolvedMemberField): void {
|
|
80
|
+
const parents = new Map<number, number>();
|
|
81
|
+
child.mapping.forEach((item, index) => {
|
|
82
|
+
const next = parent.mapping[index]!;
|
|
83
|
+
const prior = parents.get(item);
|
|
84
|
+
if (prior !== undefined && prior !== next) throw new Error("手工分组的下层成员分散在不同的上层组中。");
|
|
85
|
+
parents.set(item, next);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** @param field - Generated cache field. @param level - Resolved member ordinals. @param epoch - Calendar of the raw column.
|
|
90
|
+
* @returns Group item indexes used by its PivotTable definition. */
|
|
91
|
+
export function writeXlsxPivotMemberField(field: Element, level: WorkbookPivotResolvedMemberField, epoch: WorkbookPivotCache["dateSystem"]):
|
|
92
|
+
ReadonlyMap<string, number> {
|
|
93
|
+
const group = pivotChild(field, "fieldGroup", { base: level.sourceField, par: level.parent });
|
|
94
|
+
const discrete = pivotChild(group, "discretePr", { count: level.mapping.length });
|
|
95
|
+
for (const ordinal of level.mapping) pivotChild(discrete, "x", { v: ordinal });
|
|
96
|
+
const items = pivotChild(group, "groupItems", { count: level.items.length });
|
|
97
|
+
level.items.forEach(value => writePivotValue(items, value, epoch));
|
|
98
|
+
return new Map(level.items.map((value, index) => [workbookPivotKey(value), index]));
|
|
99
|
+
}
|