@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,98 @@
|
|
|
1
|
+
import { workbookPivotKey, type WorkbookPivotLayout, type WorkbookPivotMemberGroup, type WorkbookPivotMemberGrouping,
|
|
2
|
+
type WorkbookPivotResolvedMemberField, type WorkbookPivotSubtotal, type WorkbookPivotValue } from "@quirekit/workbook";
|
|
3
|
+
import type { XlsxPivotCache } from "../types";
|
|
4
|
+
|
|
5
|
+
/** @param layout - Native axis after date levels have been mapped. @param input - Shared native cache.
|
|
6
|
+
* @param members - Pivot field item order. @param displayed - Cache items with report-specific group aliases.
|
|
7
|
+
* @returns A canonical source layout with named group settings. */
|
|
8
|
+
export function collapseXlsxPivotMemberAxes(layout: WorkbookPivotLayout, input: XlsxPivotCache,
|
|
9
|
+
members: readonly (readonly number[])[], displayed: readonly (readonly WorkbookPivotValue[])[]): WorkbookPivotLayout {
|
|
10
|
+
if (!input.memberFields.size) return layout;
|
|
11
|
+
const groups: WorkbookPivotMemberGrouping[] = [];
|
|
12
|
+
const subtotals: WorkbookPivotSubtotal[] = [];
|
|
13
|
+
const placed = new Set([...layout.rowFields, ...layout.columnFields]);
|
|
14
|
+
const seen = new Set<number>();
|
|
15
|
+
const aggregates = new Map(layout.subtotals?.map(({ field, aggregate }) => [field, aggregate]));
|
|
16
|
+
const chains = new Map<number, WorkbookPivotResolvedMemberField[]>();
|
|
17
|
+
for (const level of input.memberFields.values()) {
|
|
18
|
+
const chain = chains.get(level.sourceField) ?? [];
|
|
19
|
+
chain[level.memberLevel - 1] = level;
|
|
20
|
+
chains.set(level.sourceField, chain);
|
|
21
|
+
}
|
|
22
|
+
if ([...layout.values, ...layout.filters].some(({ field }) => input.memberFields.has(field))) {
|
|
23
|
+
throw new Error("自定义分组用作筛选或值字段时无法直接重建。");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param axis - One native axis. @param marker - Values slot index. @returns Source fields and the adjusted Values slot. */
|
|
27
|
+
function collapse(axis: readonly number[], marker: number | undefined) {
|
|
28
|
+
const fields: number[] = [];
|
|
29
|
+
let position: number | undefined;
|
|
30
|
+
for (let index = 0; index < axis.length;) {
|
|
31
|
+
if (index === marker) position = fields.length;
|
|
32
|
+
const field = axis[index]!, group = input.memberFields.get(field);
|
|
33
|
+
const aggregate = aggregates.get(field);
|
|
34
|
+
if (!group) {
|
|
35
|
+
fields.push(field);
|
|
36
|
+
if (aggregate) subtotals.push({ field, aggregate });
|
|
37
|
+
index++;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const { sourceField, memberLevel } = group;
|
|
41
|
+
const chain = chains.get(sourceField)!.slice(0, memberLevel);
|
|
42
|
+
const next = index + chain.length;
|
|
43
|
+
const withOriginal = axis[next] === sourceField;
|
|
44
|
+
const end = next + Number(withOriginal);
|
|
45
|
+
const sequence = [...chain].reverse().map(({ field }) => field);
|
|
46
|
+
if (withOriginal) sequence.push(sourceField);
|
|
47
|
+
if (seen.has(sourceField) || !withOriginal && placed.has(sourceField)
|
|
48
|
+
|| sequence.some((field, offset) => axis[index + offset] !== field
|
|
49
|
+
|| offset > 0 && index + offset < axis.length - 1 && aggregates.get(field) !== aggregate)) {
|
|
50
|
+
throw new Error("手工分组字段与原字段的轴、层级或小计方式不一致。");
|
|
51
|
+
}
|
|
52
|
+
seen.add(sourceField);
|
|
53
|
+
const [innermost, ...parents] = chain.map((level, position) => {
|
|
54
|
+
const labels = displayed[level.field]!;
|
|
55
|
+
const child = chain[position - 1];
|
|
56
|
+
const definitions = readMemberGroups(level, labels, child, child && displayed[child.field]!);
|
|
57
|
+
const order = members[level.field]!.map(ordinal => labels[ordinal]!);
|
|
58
|
+
return { caption: level.name, groups: definitions, ...(order.length && { order }) };
|
|
59
|
+
});
|
|
60
|
+
groups.push({ field: sourceField, ...innermost!, ...(withOriginal ? {} : { showMembers: false }),
|
|
61
|
+
...(parents.length && { parents }) });
|
|
62
|
+
fields.push(sourceField);
|
|
63
|
+
if (aggregate) subtotals.push({ field: sourceField, aggregate });
|
|
64
|
+
index = end;
|
|
65
|
+
}
|
|
66
|
+
if (marker === axis.length) position = fields.length;
|
|
67
|
+
if (marker !== undefined && position === undefined) throw new Error("数据透视表的数值轴拆开了手工分组。");
|
|
68
|
+
return { fields, position };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const marker = layout.valuesAxis;
|
|
72
|
+
const rows = collapse(layout.rowFields, marker?.axis === "row" ? marker.position : undefined);
|
|
73
|
+
const columns = collapse(layout.columnFields, marker?.axis === "column" ? marker.position : undefined);
|
|
74
|
+
return { ...layout, rowFields: rows.fields, columnFields: columns.fields, memberGroups: groups, subtotals,
|
|
75
|
+
...(marker && { valuesAxis: { axis: marker.axis, position: (marker.axis === "row" ? rows : columns).position! } }) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** @param group - Original cached group members and assignment. @param labels - Effective report captions.
|
|
79
|
+
* @param child - The member level beneath this one, if any. @param childLabels - Lower report captions.
|
|
80
|
+
* @returns Named groups, with unchanged child members left to inherit their existing caption. */
|
|
81
|
+
function readMemberGroups(group: WorkbookPivotResolvedMemberField, labels: readonly WorkbookPivotValue[],
|
|
82
|
+
child: WorkbookPivotResolvedMemberField | undefined, childLabels: readonly WorkbookPivotValue[] | undefined): readonly WorkbookPivotMemberGroup[] {
|
|
83
|
+
const assignment = labels.map(() => ({ members: new Map<string, WorkbookPivotValue>(), inherited: true }));
|
|
84
|
+
group.sourceItems.forEach((value, index) => {
|
|
85
|
+
const ordinal = group.mapping[index]!;
|
|
86
|
+
const entry = assignment[ordinal]!;
|
|
87
|
+
const lower = child ? childLabels![child.mapping[index]!]! : value;
|
|
88
|
+
const key = workbookPivotKey(lower);
|
|
89
|
+
entry.inherited &&= key === workbookPivotKey(labels[ordinal]!);
|
|
90
|
+
entry.members.set(workbookPivotKey(value), value);
|
|
91
|
+
});
|
|
92
|
+
return labels.flatMap((name, index) => {
|
|
93
|
+
const { inherited, members } = assignment[index]!;
|
|
94
|
+
if (inherited) return [];
|
|
95
|
+
if (typeof name !== "string" || !name) throw new Error("自定义分组缺少有效的名称。");
|
|
96
|
+
return [{ name, members: [...members.values()] }];
|
|
97
|
+
});
|
|
98
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { WorkbookPivotNumberGroup } from "@quirekit/workbook";
|
|
2
|
+
import type { XlsxPivotCache } from "../types";
|
|
3
|
+
|
|
4
|
+
/** @param input - Shared cache fields. @param axes - Role of each field in this definition.
|
|
5
|
+
* @param members - Native item ordinals by field. @returns Numeric groups active on the row or column axis. */
|
|
6
|
+
export function readXlsxPivotNumberGroups(input: XlsxPivotCache, axes: ReadonlyMap<number, string>,
|
|
7
|
+
members: readonly (readonly number[])[]): readonly WorkbookPivotNumberGroup[] {
|
|
8
|
+
const groups: WorkbookPivotNumberGroup[] = [];
|
|
9
|
+
for (const level of input.numberFields.values()) {
|
|
10
|
+
const { field, start, end, interval, autoStart, autoEnd, integer, items } = level;
|
|
11
|
+
const axis = axes.get(field);
|
|
12
|
+
if (axis === "axisPage") throw new Error("数值分组用作报表筛选时无法映射为普通筛选。");
|
|
13
|
+
if (axis !== "axisRow" && axis !== "axisCol") continue;
|
|
14
|
+
const order = members[field]!;
|
|
15
|
+
groups.push({ field, interval, ...(autoStart ? {} : { start }), ...(autoEnd ? {} : { end }),
|
|
16
|
+
labels: { start, end, integer, items, ...(order.some((value, index) => index > 0 && value < order[index - 1]!) && { order }) } });
|
|
17
|
+
}
|
|
18
|
+
return groups;
|
|
19
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { workbookPivotAxisFieldRef, workbookPivotValuesAxis, type WorkbookPivotLayout,
|
|
3
|
+
type WorkbookPivotReportPresentation, type WorkbookPivotResultCaption } from "@quirekit/workbook";
|
|
4
|
+
import { child, readIndex } from "../../opc/xml";
|
|
5
|
+
import { decodeXlsxText, encodeXlsxText } from "../../worksheet/text";
|
|
6
|
+
import type { XlsxPivotCache } from "../types";
|
|
7
|
+
import { pivotMembers } from "../xml";
|
|
8
|
+
import { readXlsxPivotFlag } from "./extension";
|
|
9
|
+
|
|
10
|
+
/** @param root - Native definition. @param flag - Enable switch. @param caption - Replacement attribute.
|
|
11
|
+
* @param fallback - Default switch. @returns An independent non-default replacement setting. */
|
|
12
|
+
function readCaption(root: Element, flag: string, caption: string, fallback: boolean): WorkbookPivotResultCaption | undefined {
|
|
13
|
+
const enabled = readXlsxPivotFlag(root, flag) ?? fallback;
|
|
14
|
+
const text = decodeXlsxText(root.getAttribute(caption) ?? "");
|
|
15
|
+
if (enabled !== fallback || text) return { enabled, text };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param root - Native definition. @param layout - Native fields and measure positions.
|
|
19
|
+
* @param cache - Source field and derived group identities. @param blankFields - Fields flagged for blank rows.
|
|
20
|
+
* @returns Report settings in stable workbook field coordinates. */
|
|
21
|
+
export function readXlsxPivotPresentation(root: Element, layout: WorkbookPivotLayout, cache: XlsxPivotCache,
|
|
22
|
+
blankFields: ReadonlySet<number>): WorkbookPivotReportPresentation | undefined {
|
|
23
|
+
const empty = readCaption(root, "showMissing", "missingCaption", true);
|
|
24
|
+
const error = readCaption(root, "showError", "errorCaption", false);
|
|
25
|
+
let blankRows: WorkbookPivotReportPresentation["blankRows"];
|
|
26
|
+
if (blankFields.size) {
|
|
27
|
+
const ordinaryFields = cache.shared.map((_, field) => field).filter(field => !cache.calculatedFields.has(field));
|
|
28
|
+
const { rowFields } = layout;
|
|
29
|
+
const placement = workbookPivotValuesAxis(layout);
|
|
30
|
+
const leafWidth = rowFields.length + Number(layout.values.length > 1 && placement.axis === "row" && placement.position < rowFields.length);
|
|
31
|
+
// WPS stamps every ordinary field, while an individual Excel setting can add a separator after a leaf row.
|
|
32
|
+
const hasLeafSeparator = pivotMembers(child(root, "rowItems"), "i").some(item => item.getAttribute("t") === "blank"
|
|
33
|
+
&& (readIndex(item, "r") ?? 0) + pivotMembers(item, "x").length >= leafWidth);
|
|
34
|
+
if (blankFields.size === ordinaryFields.length && !hasLeafSeparator) blankRows = true;
|
|
35
|
+
else {
|
|
36
|
+
const selected = rowFields.filter(field => blankFields.has(field));
|
|
37
|
+
blankRows = selected.map(field => workbookPivotAxisFieldRef(field, cache.dateFields.get(field), cache.memberFields.get(field)));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (blankRows || empty || error) return { blankRows, empty, error };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @param caption - Authored literal. @returns SpreadsheetML attribute text without XML whitespace normalization. */
|
|
44
|
+
function captionValue(caption: WorkbookPivotResultCaption | undefined): string | undefined {
|
|
45
|
+
return caption?.text ? encodeXlsxText(caption.text).replace(/[\t\n]/gu, value => value === "\t" ? "_x0009_" : "_x000A_") : undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** @param presentation - Validated report settings. @returns Standard native result display attributes. */
|
|
49
|
+
export function xlsxPivotPresentationAttributes(presentation: WorkbookPivotReportPresentation | undefined) {
|
|
50
|
+
return { showMissing: presentation?.empty?.enabled === false ? false : undefined, missingCaption: captionValue(presentation?.empty),
|
|
51
|
+
showError: presentation?.error?.enabled || undefined, errorCaption: captionValue(presentation?.error) };
|
|
52
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { copyWorkbookPivot, formatWorkbookRange, parseWorkbookRange, planWorkbookPivot, workbookPivotAggregates, workbookPivotAxisFieldRef,
|
|
3
|
+
type WorkbookPivotFilter, type WorkbookPivotLayout, type WorkbookPivotMeasure, type WorkbookPivotTable } from "@quirekit/workbook";
|
|
4
|
+
import { v4 as uuidv4 } from "uuid";
|
|
5
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
6
|
+
import { child, isTrue, readIndex } from "../../opc/xml";
|
|
7
|
+
import { decodeXlsxText } from "../../worksheet/text";
|
|
8
|
+
import { pivotMembers } from "../xml";
|
|
9
|
+
import type { XlsxPivotCache } from "../types";
|
|
10
|
+
import { readXlsxPivotAxes } from "./axes";
|
|
11
|
+
import { collapseXlsxPivotDateAxes } from "./dates";
|
|
12
|
+
import { collapseXlsxPivotMemberAxes } from "./members";
|
|
13
|
+
import { readXlsxPivotNumberGroups } from "./numbers";
|
|
14
|
+
import { collapseXlsxPivotDisplay, readXlsxPivotDisplay } from "./display";
|
|
15
|
+
import { readXlsxPivotFlag } from "./extension";
|
|
16
|
+
import { readXlsxPivotAxisSettings } from "./field-settings/filters";
|
|
17
|
+
import { nativePivotFunctions } from "./functions";
|
|
18
|
+
import { checkPivotFieldItems, checkPivotLayoutItems } from "./items";
|
|
19
|
+
import { readXlsxPivotPresentation } from "./presentation";
|
|
20
|
+
import { readXlsxPivotReportLayout } from "./report-layout";
|
|
21
|
+
|
|
22
|
+
/** @param root - Native table definition. @param owner - Destination worksheet ID. @param input - Associated cached data.
|
|
23
|
+
* @returns Writable layout with the exact native result and filter region. */
|
|
24
|
+
export function readXlsxPivotDefinition(root: Element, owner: string, input: XlsxPivotCache): WorkbookPivotTable {
|
|
25
|
+
const showDetails = root.hasAttribute("enableDrill") ? root.getAttribute("enableDrill") : "true";
|
|
26
|
+
if (!hasKnownChildren(root, ["location", "pivotFields", "rowFields", "rowItems", "colFields", "colItems", "pageFields", "dataFields",
|
|
27
|
+
"pivotTableStyleInfo", "filters", "extLst"])
|
|
28
|
+
|| !hasKnownAttributes(root, ["name", "cacheId", "dataCaption", "grandTotalCaption", "updatedVersion", "createdVersion", "minRefreshableVersion",
|
|
29
|
+
"autoFormatId", "applyNumberFormats", "applyBorderFormats", "applyFontFormats", "applyPatternFormats", "applyAlignmentFormats", "applyWidthHeightFormats",
|
|
30
|
+
"useAutoFormatting", "compact", "outline", "compactData", "outlineData", "dataOnRows", "dataPosition", "indent", "showDrill", "rowGrandTotals", "colGrandTotals",
|
|
31
|
+
"multipleFieldFilters", "showHeaders", "enableDrill", "showMissing", "missingCaption", "showError", "errorCaption"])
|
|
32
|
+
|| !["0", "1", "false", "true"].includes(showDetails ?? "")) {
|
|
33
|
+
throw new Error("数据透视表使用了未支持的布局或扩展。");
|
|
34
|
+
}
|
|
35
|
+
const values = pivotMembers(child(root, "dataFields"), "dataField").map(readMeasure);
|
|
36
|
+
const placement = readXlsxPivotAxes(root, values.length);
|
|
37
|
+
const { rowFields, columnFields } = placement;
|
|
38
|
+
const reportLayout = readXlsxPivotReportLayout(root, rowFields, columnFields);
|
|
39
|
+
const pageFields = pivotMembers(child(root, "pageFields"), "pageField");
|
|
40
|
+
const axes = new Map<number, string>([
|
|
41
|
+
...rowFields.map(field => [field, "axisRow"] as const),
|
|
42
|
+
...columnFields.map(field => [field, "axisCol"] as const),
|
|
43
|
+
...pageFields.map(field => [readIndex(field, "fld") ?? -1, "axisPage"] as const)
|
|
44
|
+
]);
|
|
45
|
+
// A shared numeric cache can group different fields in different reports. Inactive fields still use raw item indices.
|
|
46
|
+
const cacheItems = input.shared.map((items, field) => axes.get(field) === "axisRow" || axes.get(field) === "axisCol"
|
|
47
|
+
? input.numberFields.get(field)?.items ?? items : items);
|
|
48
|
+
const { items, subtotals, displayed: shared, folded, blankFields, axisSettings } = checkPivotFieldItems(root, cacheItems, axes, new Set(values.map(value => value.field)),
|
|
49
|
+
new Set(input.memberFields.keys()), input.calculatedFields);
|
|
50
|
+
const filters = pageFields.map(page => readPageFilter(page, items, input));
|
|
51
|
+
const numberGroups = readXlsxPivotNumberGroups(input, axes, items);
|
|
52
|
+
const nativeLayout: WorkbookPivotLayout = { ...placement, filters, values, subtotals, numberGroups, reportLayout, showDetails: isTrue(showDetails),
|
|
53
|
+
showExpandCollapse: readXlsxPivotFlag(root, "showDrill"),
|
|
54
|
+
totalRow: !["0", "false"].includes(root.getAttribute("colGrandTotals") ?? ""),
|
|
55
|
+
totalColumn: !["0", "false"].includes(root.getAttribute("rowGrandTotals") ?? "") };
|
|
56
|
+
const collapsed = collapseXlsxPivotMemberAxes(collapseXlsxPivotDateAxes(nativeLayout, input, items), input, items, shared);
|
|
57
|
+
const sourceWidth = input.cache.fields.length;
|
|
58
|
+
const offsets = new Map([...input.calculatedFields.keys()].map((field, index) => [field, sourceWidth + index]));
|
|
59
|
+
const collapsedItems = [...folded].map(([field, ordinals]) => ({
|
|
60
|
+
...workbookPivotAxisFieldRef(field, input.dateFields.get(field), input.memberFields.get(field)),
|
|
61
|
+
items: ordinals.map(index => shared[field]![index]!)
|
|
62
|
+
}));
|
|
63
|
+
const reportPresentation = readXlsxPivotPresentation(root, nativeLayout, input, blankFields);
|
|
64
|
+
const fieldSettings = readXlsxPivotAxisSettings(root, [...rowFields, ...columnFields], axisSettings, shared, input, values.length);
|
|
65
|
+
let layout = { ...collapsed, collapsedItems, fieldSettings, reportPresentation, calculatedFields: [...input.calculatedFields.values()], values: values.map(measure => {
|
|
66
|
+
const resolved = collapseXlsxPivotDisplay(measure, [rowFields, columnFields], input);
|
|
67
|
+
if (measure.field < sourceWidth) return resolved;
|
|
68
|
+
const field = offsets.get(measure.field);
|
|
69
|
+
if (field === undefined) throw new Error("数据透视表的值字段未指向源列或计算字段。");
|
|
70
|
+
return { ...resolved, field };
|
|
71
|
+
}) };
|
|
72
|
+
const location = child(root, "location");
|
|
73
|
+
if (!location || !hasKnownChildren(location, [])
|
|
74
|
+
|| !hasKnownAttributes(location, ["ref", "firstHeaderRow", "firstDataRow", "firstDataCol", "rowPageCount", "colPageCount"])) {
|
|
75
|
+
throw new Error("数据透视表缺少可定位的原生输出区域。");
|
|
76
|
+
}
|
|
77
|
+
const firstHeaderRow = readIndex(location, "firstHeaderRow");
|
|
78
|
+
if (!columnFields.length && placement.valuesAxis?.axis === "column" && values.length > 1
|
|
79
|
+
&& firstHeaderRow === 1 && readIndex(location, "firstDataRow") === 2) {
|
|
80
|
+
layout = { ...layout, valuesHeaderRow: true };
|
|
81
|
+
}
|
|
82
|
+
const range = parseWorkbookRange(owner, location.getAttribute("ref") ?? "");
|
|
83
|
+
const filterRows = filters.length ? filters.length + 1 : 0;
|
|
84
|
+
const anchor = { sheetId: owner, row: range.startRow - filterRows, column: range.startColumn };
|
|
85
|
+
const plan = planWorkbookPivot(input.cache, layout, anchor);
|
|
86
|
+
if ([...input.dateFields.values()].some(field => !plan.dateFields.some(level =>
|
|
87
|
+
level.sourceField === field.sourceField && level.unit === field.unit && level.name === field.name))) {
|
|
88
|
+
throw new Error("数据透视表日期组的本地字段名称冲突。");
|
|
89
|
+
}
|
|
90
|
+
if (formatWorkbookRange(plan.tableRange) !== formatWorkbookRange(range) || plan.headerRows !== readIndex(location, "firstDataRow")
|
|
91
|
+
|| firstHeaderRow !== 1 && (columnFields.length > 0 || firstHeaderRow !== 0)
|
|
92
|
+
|| plan.labelColumns !== readIndex(location, "firstDataCol") || (readIndex(location, "rowPageCount") ?? 0) !== filters.length
|
|
93
|
+
|| (readIndex(location, "colPageCount") ?? 0) !== Number(Boolean(filters.length))) {
|
|
94
|
+
throw new Error("数据透视表缓存无法还原其原生区域。");
|
|
95
|
+
}
|
|
96
|
+
const style = child(root, "pivotTableStyleInfo");
|
|
97
|
+
if (style && (!hasKnownAttributes(style, ["name", "showRowHeaders", "showColHeaders", "showRowStripes", "showColStripes", "showLastColumn"])
|
|
98
|
+
|| !hasKnownChildren(style, []) || style.getAttribute("name") !== "PivotStyleLight16"
|
|
99
|
+
|| ["showRowHeaders", "showColHeaders", "showLastColumn"].some(key => !isTrue(style.getAttribute(key)))
|
|
100
|
+
|| ["showRowStripes", "showColStripes"].some(key => isTrue(style.getAttribute(key))))) {
|
|
101
|
+
throw new Error("数据透视表使用了未支持的原生样式。");
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
checkPivotLayoutItems(root, plan, nativeLayout, items, shared);
|
|
105
|
+
} catch {
|
|
106
|
+
// External producers can sort field items independently of the source cache. Accept the
|
|
107
|
+
// resulting order only if it reconstructs all native tuples and subtotal positions.
|
|
108
|
+
layout = { ...layout, fieldItemOrder: [...layout.rowFields, ...layout.columnFields].filter(field => !input.dateFields.has(field) && !input.numberFields.has(field)).map(field => ({
|
|
109
|
+
field, items: items[field]!.map(index => shared[field]![index]!)
|
|
110
|
+
})) };
|
|
111
|
+
const ordered = planWorkbookPivot(input.cache, layout, anchor);
|
|
112
|
+
checkPivotLayoutItems(root, ordered, nativeLayout, items, shared);
|
|
113
|
+
}
|
|
114
|
+
return copyWorkbookPivot({ id: uuidv4(), name: decodeXlsxText(root.getAttribute("name") ?? ""), source: input.source,
|
|
115
|
+
output: plan.output, cache: input.cache, ...layout });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** @param node - Native summary. @returns Supported measure with the native header caption. */
|
|
119
|
+
function readMeasure(node: Element): WorkbookPivotMeasure {
|
|
120
|
+
const field = readIndex(node, "fld");
|
|
121
|
+
const measure = node.getAttribute("subtotal") || "sum";
|
|
122
|
+
const aggregate = workbookPivotAggregates.find(aggregate => nativePivotFunctions[aggregate].measure === measure);
|
|
123
|
+
const caption = node.getAttribute("name");
|
|
124
|
+
if (field === undefined || !aggregate || !caption
|
|
125
|
+
|| !hasKnownAttributes(node, ["name", "fld", "subtotal", "baseField", "baseItem", "showDataAs", "numFmtId"])) {
|
|
126
|
+
throw new Error("数据透视表含未支持的汇总方式或数值格式。");
|
|
127
|
+
}
|
|
128
|
+
const display = readXlsxPivotDisplay(node);
|
|
129
|
+
return { field, aggregate, caption: decodeXlsxText(caption), ...(display && { display }) };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @param node - Native report filter. @param items - Cache item mapping. @param input - Cached source.
|
|
133
|
+
* @returns All items or the selected typed value. */
|
|
134
|
+
function readPageFilter(node: Element, items: readonly (readonly number[])[], input: XlsxPivotCache): WorkbookPivotFilter {
|
|
135
|
+
const field = readIndex(node, "fld");
|
|
136
|
+
const item = readIndex(node, "item");
|
|
137
|
+
if (field === undefined || field >= items.length || !hasKnownAttributes(node, ["fld", "item", "hier"]) || !hasKnownChildren(node, [])
|
|
138
|
+
|| !["", "-1"].includes(node.getAttribute("hier") ?? "")
|
|
139
|
+
|| node.hasAttribute("item") && (item === undefined || items[field]![item] === undefined)) {
|
|
140
|
+
throw new Error("数据透视表含未支持的筛选器。");
|
|
141
|
+
}
|
|
142
|
+
return { field, ...(item === undefined ? {} : { equals: input.shared[field]![items[field]![item]!]! }) };
|
|
143
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { WorkbookPivotReportLayout } from "@quirekit/workbook";
|
|
3
|
+
import { child, readIndex } from "../../opc/xml";
|
|
4
|
+
import { pivotMembers } from "../xml";
|
|
5
|
+
import { readXlsxPivotFieldRepeat, readXlsxPivotFlag, readXlsxPivotRepeatDefault } from "./extension";
|
|
6
|
+
|
|
7
|
+
/** @param root - Native report definition. @param rowFields - Indices of the native row axis.
|
|
8
|
+
* @param columnFields - Indices of the native column axis.
|
|
9
|
+
* @returns A uniform row form and label policy, or legacy tabular behavior. */
|
|
10
|
+
export function readXlsxPivotReportLayout(root: Element, rowFields: readonly number[], columnFields: readonly number[]): WorkbookPivotReportLayout | undefined {
|
|
11
|
+
const compact = readXlsxPivotFlag(root, "compact") ?? true;
|
|
12
|
+
const outline = readXlsxPivotFlag(root, "outline") ?? false;
|
|
13
|
+
const indent = readIndex(root, "indent");
|
|
14
|
+
if ((readXlsxPivotFlag(root, "compactData") ?? compact) !== compact
|
|
15
|
+
|| (readXlsxPivotFlag(root, "outlineData") ?? outline) !== outline
|
|
16
|
+
|| compact && root.hasAttribute("indent") && indent !== 0 && indent !== 1) {
|
|
17
|
+
throw new Error("数据透视表使用了未支持的混合布局或缩进。");
|
|
18
|
+
}
|
|
19
|
+
const form = compact ? "compact" : outline ? "outline" : "tabular";
|
|
20
|
+
const fields = pivotMembers(child(root, "pivotFields"), "pivotField");
|
|
21
|
+
const repeatDefault = readXlsxPivotRepeatDefault(root);
|
|
22
|
+
const repeat = fields.map(readXlsxPivotFieldRepeat);
|
|
23
|
+
const axes = [...rowFields, ...columnFields];
|
|
24
|
+
const labelPolicies = new Set(axes.map(index => repeat[index] ?? repeatDefault ?? false));
|
|
25
|
+
if (labelPolicies.size > 1) throw new Error("数据透视表含逐字段的混合标签显示设置。");
|
|
26
|
+
for (const index of rowFields) {
|
|
27
|
+
const field = fields[index];
|
|
28
|
+
if (!field) throw new Error("数据透视表的行字段超出了定义范围。");
|
|
29
|
+
const fieldCompact = readXlsxPivotFlag(field, "compact") ?? compact;
|
|
30
|
+
const fieldOutline = readXlsxPivotFlag(field, "outline") ?? outline;
|
|
31
|
+
if (fieldCompact !== compact || !compact && fieldOutline !== outline) {
|
|
32
|
+
throw new Error("数据透视表含不同显示形式的行字段。");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// Older QuireKit exports without a report extension used repeated tabular labels.
|
|
36
|
+
if (form === "tabular" && !child(root, "extLst") && repeatDefault === undefined
|
|
37
|
+
&& axes.every(index => repeat[index] === undefined)) return;
|
|
38
|
+
return { form, repeatLabels: labelPolicies.has(true) || !axes.length && repeatDefault === true };
|
|
39
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { isWorkbookPivotMeasureFilter, formatWorkbookRange, workbookPivotKey, workbookPivotValuesAxis, type WorkbookPivotAxisEntry, type WorkbookPivotPlan, type WorkbookPivotTable,
|
|
3
|
+
type WorkbookPivotValue } from "@quirekit/workbook";
|
|
4
|
+
import { writePart } from "../../opc/xml";
|
|
5
|
+
import { encodeXlsxText } from "../../worksheet/text";
|
|
6
|
+
import { pivotAttributes, pivotChild, pivotXml } from "../xml";
|
|
7
|
+
import { writeXlsxPivotDisplay } from "./display";
|
|
8
|
+
import { writeXlsxPivotRepeat } from "./extension";
|
|
9
|
+
import { writeXlsxPivotSortScope, xlsxPivotMemberHidden } from "./field-settings/field";
|
|
10
|
+
import { writeXlsxPivotFilters } from "./field-settings/filters";
|
|
11
|
+
import { nativePivotFunctions, nativePivotSubtotalType } from "./functions";
|
|
12
|
+
import { pivotAxisMeasureMarker } from "./items";
|
|
13
|
+
import { xlsxPivotPresentationAttributes } from "./presentation";
|
|
14
|
+
|
|
15
|
+
/** @param path - Native table part. @param table - Committed layout and cache.
|
|
16
|
+
* @param cacheId - Workbook-local cache ID. @param indexes - Shared item indexes in cache field order.
|
|
17
|
+
* @param plan - Expanded output and date fields used to write the cache.
|
|
18
|
+
* @returns Native pivot definition aligned with the saved worksheet cells. */
|
|
19
|
+
export function writeXlsxPivotDefinition(path: string, table: WorkbookPivotTable, cacheId: number,
|
|
20
|
+
indexes: readonly ReadonlyMap<string, number>[], plan: WorkbookPivotPlan): Uint8Array {
|
|
21
|
+
const { rowFields, columnFields, filters, values } = plan.layout;
|
|
22
|
+
const document = pivotXml("pivotTableDefinition", path);
|
|
23
|
+
const root = document.documentElement!;
|
|
24
|
+
const placement = workbookPivotValuesAxis(plan.layout);
|
|
25
|
+
const rowMeasure = values.length > 1 && placement.axis === "row" ? placement.position : undefined;
|
|
26
|
+
const columnMeasure = values.length > 1 && placement.axis === "column" ? placement.position : undefined;
|
|
27
|
+
const { reportLayout } = plan.layout;
|
|
28
|
+
const compact = reportLayout?.form === "compact";
|
|
29
|
+
const top = reportLayout !== undefined && reportLayout.form !== "tabular";
|
|
30
|
+
pivotAttributes(root, { name: encodeXlsxText(table.name), cacheId, dataCaption: "值", grandTotalCaption: "总计",
|
|
31
|
+
createdVersion: reportLayout ? 5 : 3, updatedVersion: reportLayout ? 5 : 3, minRefreshableVersion: 3,
|
|
32
|
+
compact, compactData: compact, outline: top, outlineData: top, indent: compact ? 1 : undefined,
|
|
33
|
+
dataOnRows: placement.axis === "row" || undefined, dataPosition: plan.layout.valuesAxis?.position,
|
|
34
|
+
rowGrandTotals: table.totalColumn !== false, colGrandTotals: table.totalRow !== false,
|
|
35
|
+
showDrill: table.showExpandCollapse === false ? false : undefined,
|
|
36
|
+
enableDrill: table.showDetails === false ? false : undefined,
|
|
37
|
+
...xlsxPivotPresentationAttributes(table.reportPresentation) });
|
|
38
|
+
pivotChild(root, "location", { ref: formatWorkbookRange(plan.tableRange), firstHeaderRow: plan.headerRows > 1 ? 1 : 0,
|
|
39
|
+
firstDataRow: plan.headerRows, firstDataCol: plan.labelColumns,
|
|
40
|
+
rowPageCount: filters.length || undefined, colPageCount: filters.length ? 1 : undefined });
|
|
41
|
+
|
|
42
|
+
const fields = pivotChild(root, "pivotFields", { count: indexes.length });
|
|
43
|
+
const fieldAxes = new Map<number, string>([
|
|
44
|
+
...rowFields.map(field => [field, "axisRow"] as const),
|
|
45
|
+
...columnFields.map(field => [field, "axisCol"] as const),
|
|
46
|
+
...filters.map(({ field }) => [field, "axisPage"] as const)
|
|
47
|
+
]);
|
|
48
|
+
const fieldsBySubtotal = new Map(plan.layout.subtotals?.map(({ field, aggregate }) => [field, aggregate]));
|
|
49
|
+
const preferredOrder = new Map(plan.layout.fieldItemOrder?.map(({ field, items }) => [field, items]));
|
|
50
|
+
const folded = new Map(plan.layout.collapsedItems?.map(({ field, items }) =>
|
|
51
|
+
[field, new Set(items.map(workbookPivotKey))]));
|
|
52
|
+
const blankFields = new Set(plan.blankRowFields);
|
|
53
|
+
const byField = new Map(plan.layout.fieldSettings?.map(entry => [entry.field, entry]));
|
|
54
|
+
const allFieldsAddBlankRows = table.reportPresentation?.blankRows === true;
|
|
55
|
+
const ordinals = indexes.map((items, field) => {
|
|
56
|
+
const axis = fieldAxes.get(field);
|
|
57
|
+
const subtotal = fieldsBySubtotal.get(field);
|
|
58
|
+
const settings = byField.get(field);
|
|
59
|
+
const direction = typeof settings?.sort === "object" ? settings.sort.direction : settings?.sort;
|
|
60
|
+
const membersFilter = settings?.filter?.kind === "members" ? settings.filter : undefined;
|
|
61
|
+
const preference = preferredOrder.get(field);
|
|
62
|
+
const ordered = preference ? orderFieldMembers(items, preference) : items;
|
|
63
|
+
const calculated = field >= table.cache.fields.length
|
|
64
|
+
&& field < table.cache.fields.length + (plan.layout.calculatedFields?.length ?? 0);
|
|
65
|
+
const node = pivotChild(fields, "pivotField", { axis, dataField: values.some(value => value.field === field) || undefined,
|
|
66
|
+
showAll: false, defaultSubtotal: subtotal === "automatic", compact, outline: top,
|
|
67
|
+
sortType: direction === "asc" ? "ascending" : direction === "desc" ? "descending" : "manual",
|
|
68
|
+
measureFilter: isWorkbookPivotMeasureFilter(settings?.filter) || undefined,
|
|
69
|
+
includeNewItemsInFilter: membersFilter?.mode === "exclude" || undefined,
|
|
70
|
+
hideNewItems: membersFilter?.mode === "include" || undefined,
|
|
71
|
+
insertBlankRow: !calculated && (allFieldsAddBlankRows || blankFields.has(field)) || undefined,
|
|
72
|
+
...(calculated && { dragToCol: false, dragToPage: false, dragToRow: false }),
|
|
73
|
+
subtotalTop: subtotal ? top && axis === "axisRow" : undefined,
|
|
74
|
+
...(subtotal && subtotal !== "automatic" && { [nativePivotFunctions[subtotal].flag]: true }) });
|
|
75
|
+
if (axis && (ordered.size || subtotal)) {
|
|
76
|
+
const members = pivotChild(node, "items", { count: ordered.size + Number(Boolean(subtotal)) });
|
|
77
|
+
const closed = folded.get(field);
|
|
78
|
+
const isHidden = xlsxPivotMemberHidden(membersFilter);
|
|
79
|
+
for (const [key, index] of ordered) pivotChild(members, "item", { x: index, h: isHidden(key) || undefined, sd: closed?.has(key) ? false : undefined });
|
|
80
|
+
if (subtotal) pivotChild(members, "item", { t: nativePivotSubtotalType(subtotal) });
|
|
81
|
+
}
|
|
82
|
+
writeXlsxPivotSortScope(node, settings?.sort);
|
|
83
|
+
if (reportLayout?.repeatLabels && (axis === "axisRow" || axis === "axisCol")) writeXlsxPivotRepeat(node, true, true);
|
|
84
|
+
return preference ? new Map([...ordered.keys()].map((key, index) => [key, index])) : items;
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// Each worksheet slot has the same item order as its native axis. Grouping items
|
|
88
|
+
// refer to pivot field ordinals and the synthetic field refers to the measure list.
|
|
89
|
+
if (rowFields.length || rowMeasure !== undefined) {
|
|
90
|
+
writeAxisFields(root, "rowFields", rowFields, rowMeasure);
|
|
91
|
+
writeAxisItems(root, "rowItems", rowFields, plan.rowEntries, rowMeasure, ordinals, top);
|
|
92
|
+
}
|
|
93
|
+
if (columnFields.length || columnMeasure !== undefined) {
|
|
94
|
+
writeAxisFields(root, "colFields", columnFields, columnMeasure);
|
|
95
|
+
writeAxisItems(root, "colItems", columnFields, plan.columnEntries, columnMeasure, ordinals);
|
|
96
|
+
}
|
|
97
|
+
if (filters.length) {
|
|
98
|
+
const pages = pivotChild(root, "pageFields", { count: filters.length });
|
|
99
|
+
for (const { field, equals } of filters) {
|
|
100
|
+
pivotChild(pages, "pageField", { fld: field, hier: -1, item: equals === undefined ? undefined : ordinals[field]!.get(workbookPivotKey(equals)) });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const measures = pivotChild(root, "dataFields", { count: values.length });
|
|
104
|
+
values.forEach(({ field, aggregate, display }, index) => {
|
|
105
|
+
const measure = pivotChild(measures, "dataField", {
|
|
106
|
+
name: encodeXlsxText(plan.captions[index]!), fld: field, subtotal: nativePivotFunctions[aggregate].measure
|
|
107
|
+
});
|
|
108
|
+
writeXlsxPivotDisplay(measure, display);
|
|
109
|
+
});
|
|
110
|
+
pivotChild(root, "pivotTableStyleInfo", { name: "PivotStyleLight16", showRowHeaders: true, showColHeaders: true,
|
|
111
|
+
showRowStripes: false, showColStripes: false, showLastColumn: true });
|
|
112
|
+
writeXlsxPivotFilters(root, plan.layout.fieldSettings);
|
|
113
|
+
if (reportLayout) writeXlsxPivotRepeat(root, reportLayout.repeatLabels);
|
|
114
|
+
return writePart(document);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** @param source - Cache indexes. @param preference - Ordered native field members.
|
|
118
|
+
* @returns Cache indexes ordered by current field membership, then by source order for new entries. */
|
|
119
|
+
function orderFieldMembers(source: ReadonlyMap<string, number>, preference: readonly WorkbookPivotValue[]): ReadonlyMap<string, number> {
|
|
120
|
+
const order = new Map<string, number>();
|
|
121
|
+
for (const value of preference) {
|
|
122
|
+
const key = workbookPivotKey(value);
|
|
123
|
+
const index = source.get(key);
|
|
124
|
+
if (index !== undefined) order.set(key, index);
|
|
125
|
+
}
|
|
126
|
+
for (const [key, index] of source) if (!order.has(key)) order.set(key, index);
|
|
127
|
+
return order;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** @param root - Native definition. @param name - Axis element. @param fields - Grouping fields.
|
|
131
|
+
* @param position - Boundary of the synthetic Values field, when visible. */
|
|
132
|
+
function writeAxisFields(root: Element, name: string, fields: readonly number[], position: number | undefined): void {
|
|
133
|
+
const indexes = [...fields];
|
|
134
|
+
if (position !== undefined) indexes.splice(position, 0, -2);
|
|
135
|
+
const axis = pivotChild(root, name, { count: indexes.length });
|
|
136
|
+
for (const index of indexes) pivotChild(axis, "field", { x: index });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** @param root - Native definition. @param name - Axis item element. @param fields - Grouping fields.
|
|
140
|
+
* @param entries - Ordered display slots. @param position - Optional measure field boundary.
|
|
141
|
+
* @param indexes - Cache item indexes aligned to native pivot field items. @param top - Whether the row item is a leading parent. */
|
|
142
|
+
function writeAxisItems(root: Element, name: string, fields: readonly number[], entries: readonly WorkbookPivotAxisEntry[],
|
|
143
|
+
position: number | undefined, indexes: readonly ReadonlyMap<string, number>[], top = false): void {
|
|
144
|
+
const list = pivotChild(root, name, { count: entries.length });
|
|
145
|
+
for (const { group, measure } of entries) {
|
|
146
|
+
const type = group.total ? "grand" : group.blank ? "blank" : group.subtotal && !top ? nativePivotSubtotalType(group.subtotal) : undefined;
|
|
147
|
+
const item = pivotChild(list, "i", { t: type, i: measure || undefined });
|
|
148
|
+
if (group.total) {
|
|
149
|
+
pivotChild(item, "x");
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const members = group.items.map((value, offset) => indexes[fields[offset]!]!.get(workbookPivotKey(value)));
|
|
153
|
+
const marker = pivotAxisMeasureMarker(group, position);
|
|
154
|
+
if (marker !== undefined) members.splice(marker, 0, measure);
|
|
155
|
+
for (const member of members) pivotChild(item, "x", { v: member });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { formatWorkbookRange, openWorkbook, parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
5
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
6
|
+
|
|
7
|
+
it("opens the WPS Web calculated field cache and retains dependent formulas after renaming and refreshing", async () => {
|
|
8
|
+
const bytes = readFileSync(new URL("../../../test/fixtures/native-pivot-calculated-fields.xlsx", import.meta.url));
|
|
9
|
+
const file = openXlsx("Calculated fields from WPS Web", bytes);
|
|
10
|
+
expect(file.restrictions).toEqual([]);
|
|
11
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
12
|
+
try {
|
|
13
|
+
const pivot = workbook.pivotTables()[0]!;
|
|
14
|
+
const sheetId = pivot.output.sheetId;
|
|
15
|
+
const sourceSheet = pivot.source.sheetId;
|
|
16
|
+
const grand = { sheetId, row: 12, column: 21 };
|
|
17
|
+
expect(workbook.readCell(grand).result).toEqual({ status: "value", value: 44100 });
|
|
18
|
+
expect(workbook.readCell({ ...grand, column: 22 }).result).toEqual({ status: "value", value: 44110 });
|
|
19
|
+
expect(pivot.cache.fields).toHaveLength(5);
|
|
20
|
+
expect(pivot.calculatedFields?.map(({ formula }) => formula)).toEqual(["=金额*金额", "=IF(金额=0,0,金额平方+10)"]);
|
|
21
|
+
const source = workbook.readCell({ sheetId: sourceSheet, row: 1, column: 13 }).result;
|
|
22
|
+
if (source.status !== "value" || typeof source.value !== "number") throw new Error("Missing WPS sample amount");
|
|
23
|
+
await workbook.commit(workbook.prepare({ operationId: "refresh-calculated", baseRevision: workbook.revision, commands: [
|
|
24
|
+
{ name: "setCells", target: parseWorkbookRange(sourceSheet, "N1"), params: { value: "净 金额" } },
|
|
25
|
+
{ name: "setCells", target: parseWorkbookRange(sourceSheet, "N2"), params: { value: source.value + 10 } },
|
|
26
|
+
{ name: "refreshPivotTable", target: parseWorkbookRange(sheetId, "A3"), params: { id: pivot.id } }
|
|
27
|
+
] }).id);
|
|
28
|
+
const saved = openXlsx("Refreshed calculated fields", file.write(workbook.snapshot()));
|
|
29
|
+
expect(saved.restrictions).toEqual([]);
|
|
30
|
+
const recalculated = saved.snapshot.pivotTables?.[0];
|
|
31
|
+
expect(recalculated?.calculatedFields?.map(({ formula }) => formula)).toEqual([
|
|
32
|
+
"='净 金额'*'净 金额'", "=IF('净 金额'=0,0,金额平方+10)"
|
|
33
|
+
]);
|
|
34
|
+
expect(workbook.readCell(grand).result).toEqual({ status: "value", value: 48400 });
|
|
35
|
+
expect(workbook.readCell({ ...grand, column: 22 }).result).toEqual({ status: "value", value: 48410 });
|
|
36
|
+
await workbook.undo("undo-calculated-refresh");
|
|
37
|
+
expect(workbook.readCell(grand).result).toEqual({ status: "value", value: 44100 });
|
|
38
|
+
expect(workbook.pivotTables()[0]!.calculatedFields).toEqual(pivot.calculatedFields);
|
|
39
|
+
} finally { await workbook.close(); }
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("opens WPS for Mac's extra Values heading after native calculation and preserves it during formula edits", async () => {
|
|
43
|
+
const bytes = readFileSync(new URL("../../../test/fixtures/wps-refreshed-pivot-calculated-fields.xlsx", import.meta.url));
|
|
44
|
+
const file = openXlsx("WPS worksheet with a Values heading", bytes);
|
|
45
|
+
expect(file.restrictions).toEqual([]);
|
|
46
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
47
|
+
try {
|
|
48
|
+
const pivot = workbook.pivotTables()[0]!;
|
|
49
|
+
expect(formatWorkbookRange(pivot.output)).toBe("A1:D5");
|
|
50
|
+
const sheetId = pivot.output.sheetId;
|
|
51
|
+
const grand = { sheetId, row: 4, column: 3 };
|
|
52
|
+
expect(workbook.readCell(grand).result).toEqual({ status: "value", value: expect.closeTo(1960000 / 1200, 8) });
|
|
53
|
+
expect(pivot.calculatedFields).toEqual([{ name: "应收合计 平方", formula: "=应收金额^2" },
|
|
54
|
+
{ name: "应收倍率", formula: "='应收合计 平方'/已收金额" }]);
|
|
55
|
+
await workbook.commit(workbook.prepare({ operationId: "edit-values-heading", baseRevision: workbook.revision, commands: [
|
|
56
|
+
{ name: "setPivotTable", target: parseWorkbookRange(sheetId, "A1"), params: {
|
|
57
|
+
id: pivot.id, name: pivot.name, source: { sheetId: pivot.source.sheetId, range: formatWorkbookRange(pivot.source) },
|
|
58
|
+
rowFields: pivot.rowFields, columnFields: pivot.columnFields, filters: pivot.filters, values: pivot.values,
|
|
59
|
+
calculatedFields: pivot.calculatedFields!.map(({ name, formula }, index) => ({ name, formula: index ? formula + "+10" : formula }))
|
|
60
|
+
} }
|
|
61
|
+
] }).id);
|
|
62
|
+
expect(workbook.readCell({ sheetId, row: 0, column: 1 }).result).toEqual({ status: "value", value: "值" });
|
|
63
|
+
expect(workbook.readCell(grand).result).toEqual({ status: "value", value: 1960000 / 1200 + 10 });
|
|
64
|
+
const reopened = openXlsx("Saved with Values heading", file.write(workbook.snapshot()));
|
|
65
|
+
expect(reopened.restrictions).toEqual([]);
|
|
66
|
+
expect(formatWorkbookRange(reopened.snapshot.pivotTables![0]!.output)).toBe("A1:D5");
|
|
67
|
+
} finally { await workbook.close(); }
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("writes calculated fields before synthetic groups and preserves an unsupported native formula without conversion", async () => {
|
|
71
|
+
const records = [["Region", "Sales", "Cost"], ["East", 50, 0], ["West", 40, 20], ["Other", 50, 0]];
|
|
72
|
+
const snapshot: WorkbookSnapshot = { version: 1, id: "calc-groups", name: "Calc Groups", revision: 0, sheets: [
|
|
73
|
+
{ id: "data", name: "Data", cells: records.flatMap((record, row) =>
|
|
74
|
+
record.map((value, column) => ({ row, column, input: { kind: "value", value } }))) },
|
|
75
|
+
{ id: "report", name: "Report", cells: [] }
|
|
76
|
+
] };
|
|
77
|
+
const workbook = await openWorkbook(snapshot);
|
|
78
|
+
try {
|
|
79
|
+
await workbook.commit(workbook.prepare({ operationId: "calc-groups", baseRevision: workbook.revision, commands: [
|
|
80
|
+
{ name: "setPivotTable", target: parseWorkbookRange("report", "A1"), params: {
|
|
81
|
+
name: "Margin", source: { sheetId: "data", range: "A1:C4" }, rowFields: [0], columnFields: [], filters: [],
|
|
82
|
+
calculatedFields: [{ name: "倍率", formula: "=Sales/Cost" }],
|
|
83
|
+
values: [{ field: 3, aggregate: "sum" }],
|
|
84
|
+
memberGroups: [{ field: 0, groups: [{ name: "Markets", members: ["East", "West"] }] }]
|
|
85
|
+
} }
|
|
86
|
+
] }).id);
|
|
87
|
+
const bytes = createXlsx(workbook.snapshot());
|
|
88
|
+
const parts = unzipSync(bytes);
|
|
89
|
+
const definition = Object.keys(parts).find(path => /^xl\/pivotCache\/pivotCacheDefinition\d+\.xml$/u.test(path))!;
|
|
90
|
+
const recordsPath = Object.keys(parts).find(path => /^xl\/pivotCache\/pivotCacheRecords\d+\.xml$/u.test(path))!;
|
|
91
|
+
const native = strFromU8(parts[definition]!);
|
|
92
|
+
expect(native).toMatch(/<cacheField name="倍率" numFmtId="0" formula="Sales\/Cost" databaseField="0"\/>/u);
|
|
93
|
+
expect(native).toContain('<fieldGroup par="4"');
|
|
94
|
+
expect(strFromU8(parts[recordsPath]!)).toMatch(/<r>(?:<x v="\d+"\/>){3}<\/r>/u);
|
|
95
|
+
const restored = openXlsx("Grouped calculated field", bytes);
|
|
96
|
+
expect(restored.restrictions).toEqual([]);
|
|
97
|
+
expect(restored.snapshot.pivotTables?.[0]).toMatchObject({ calculatedFields: [{ name: "倍率", formula: "=Sales/Cost" }],
|
|
98
|
+
values: [{ field: 3 }], memberGroups: [{ field: 0 }] });
|
|
99
|
+
expect(restored.snapshot.sheets[1]?.cells.some(({ input }) => input?.kind === "error" && input.code === "#DIV/0!")).toBe(true);
|
|
100
|
+
parts[definition] = strToU8(native.replace("Sales/Cost", "INDIRECT("A1")"));
|
|
101
|
+
expect(openXlsx("Unsupported calculated field", zipSync(parts)).restrictions).toContain("未支持的数据透视表、缓存或工作表关系");
|
|
102
|
+
} finally { await workbook.close(); }
|
|
103
|
+
});
|