@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,85 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { strFromU8, unzipSync } from "fflate";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { formatWorkbookRange, openWorkbook, parseWorkbookRange } from "@quirekit/workbook";
|
|
5
|
+
import { openXlsx } from "../../index";
|
|
6
|
+
|
|
7
|
+
const bytes = readFileSync(new URL("../../../test/fixtures/wps-pivot-measure-settings.xlsx", import.meta.url));
|
|
8
|
+
|
|
9
|
+
it("opens WPS reports with value rules, all three rank units and measure sort scopes", async () => {
|
|
10
|
+
const file = openXlsx("WPS PivotTable value settings", bytes);
|
|
11
|
+
expect(file.restrictions).toEqual([]);
|
|
12
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
13
|
+
try {
|
|
14
|
+
const tables = workbook.pivotTables();
|
|
15
|
+
expect(tables.map(({ name, output }) => [name, formatWorkbookRange(output)])).toEqual([
|
|
16
|
+
["QuarterValueSort", "A3:I12"], ["TopQuarter", "A3:I10"], ["BatchOver70", "A3:I9"], ["QuarterThenBatch", "A3:I9"],
|
|
17
|
+
["NoQuarter", "A3:I6"], ["TopPercent", "A3:I10"], ["TopSum", "A3:I14"], ["RegionOutside", "A3:F14"], ["RegionValueSort", "A3:I14"]
|
|
18
|
+
]);
|
|
19
|
+
expect(tables[0]?.fieldSettings).toContainEqual({ field: 2, sort: { direction: "desc", measure: 0 } });
|
|
20
|
+
expect(tables[1]?.fieldSettings).toContainEqual({ field: 2, sort: { direction: "desc", measure: 0 },
|
|
21
|
+
filter: { kind: "rank", measure: 0, order: "top", unit: "items", count: 1 } });
|
|
22
|
+
expect(tables[3]?.fieldSettings?.map(entry => entry.field)).toEqual([2, 4]);
|
|
23
|
+
expect(tables[5]?.fieldSettings).toContainEqual({ field: 2, sort: "asc",
|
|
24
|
+
filter: { kind: "rank", measure: 0, order: "top", unit: "percent", count: 50 } });
|
|
25
|
+
expect(tables[6]?.fieldSettings).toContainEqual({ field: 2, sort: "asc",
|
|
26
|
+
filter: { kind: "rank", measure: 0, order: "top", unit: "sum", count: 150 } });
|
|
27
|
+
expect(tables[7]?.fieldSettings).toContainEqual({ field: 0,
|
|
28
|
+
filter: { kind: "value", measure: 0, operator: "notBetween", first: 95, second: 105 } });
|
|
29
|
+
expect(tables[8]?.fieldSettings).toContainEqual({ field: 0, sort: { direction: "asc", measure: 0 } });
|
|
30
|
+
const values = tables.map(({ output }) => {
|
|
31
|
+
const { result } = workbook.readCell({ sheetId: output.sheetId, row: output.endRow, column: output.endColumn });
|
|
32
|
+
return "value" in result ? result.value : undefined;
|
|
33
|
+
});
|
|
34
|
+
expect(values).toEqual([160, 120, 100, 100, null, 120, 210, 110, 210]);
|
|
35
|
+
const ranked = tables[1]!;
|
|
36
|
+
const { sheetId } = ranked.output;
|
|
37
|
+
await workbook.commit(workbook.prepare({ operationId: "refresh-ranked-report", baseRevision: workbook.revision, commands: [
|
|
38
|
+
{ name: "setCells", target: parseWorkbookRange(ranked.source.sheetId, "N7"), params: { value: 0 } },
|
|
39
|
+
{ name: "refreshPivotTable", target: parseWorkbookRange(sheetId, "A3"), params: { id: ranked.id } }
|
|
40
|
+
] }).id);
|
|
41
|
+
expect(workbook.pivotTables()[1]?.fieldSettings).toEqual(ranked.fieldSettings);
|
|
42
|
+
expect(workbook.readCell({ sheetId, row: 5, column: 0 }).result).toMatchObject({ value: "Q1" });
|
|
43
|
+
expect(workbook.readCell({ sheetId, row: 9, column: 8 }).result).toMatchObject({ value: 90 });
|
|
44
|
+
expect(workbook.pivotTables()[5]?.cache.records).toEqual(tables[5]?.cache.records);
|
|
45
|
+
await workbook.undo("undo-ranked-refresh");
|
|
46
|
+
expect(workbook.readCell({ sheetId, row: 9, column: 8 }).result).toMatchObject({ value: 120 });
|
|
47
|
+
} finally { await workbook.close(); }
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("saves edited numeric evaluation order and reloads value rules and bottom rank as native settings", async () => {
|
|
51
|
+
const file = openXlsx("Value settings", bytes);
|
|
52
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
53
|
+
try {
|
|
54
|
+
const ordered = workbook.pivotTables().find(table => table.name === "QuarterThenBatch")!;
|
|
55
|
+
const ranked = workbook.pivotTables().find(table => table.name === "TopQuarter")!;
|
|
56
|
+
const orderedTarget = parseWorkbookRange(ordered.output.sheetId, "A3");
|
|
57
|
+
await workbook.commit(workbook.prepare({ operationId: "rewrite-native-measures", baseRevision: workbook.revision, commands: [
|
|
58
|
+
{ name: "setPivotFieldSettings", target: orderedTarget, params: { id: ordered.id, field: 2,
|
|
59
|
+
filter: { kind: "value", measure: 0, operator: "greaterThan", first: 105 } } },
|
|
60
|
+
{ name: "setPivotFieldSettings", target: parseWorkbookRange(ranked.output.sheetId, "A3"), params: { id: ranked.id, field: 2,
|
|
61
|
+
filter: { kind: "rank", measure: 0, order: "bottom", unit: "percent", count: 40 } } }
|
|
62
|
+
] }).id);
|
|
63
|
+
|
|
64
|
+
const written = file.write(workbook.snapshot());
|
|
65
|
+
const native = Object.entries(unzipSync(written)).filter(([path]) => /^xl\/pivotTables\/pivotTable\d+\.xml$/u.test(path))
|
|
66
|
+
.map(([, data]) => strFromU8(data));
|
|
67
|
+
const orderedXml = native.find(xml => xml.includes('name="QuarterThenBatch"'));
|
|
68
|
+
expect(orderedXml).toMatch(/fld="4" type="valueGreaterThan" id="0" evalOrder="0" iMeasureFld="0"/u);
|
|
69
|
+
expect(orderedXml).toMatch(/fld="2" type="valueGreaterThan" id="1" evalOrder="1" iMeasureFld="0"/u);
|
|
70
|
+
const rankedXml = native.find(xml => xml.includes('name="TopQuarter"'));
|
|
71
|
+
expect(rankedXml).toContain("<autoSortScope>");
|
|
72
|
+
expect(rankedXml).toMatch(/<top10 [^>]*top="0" percent="1"/u);
|
|
73
|
+
const saved = openXlsx("Reopened value settings", written);
|
|
74
|
+
expect(saved.restrictions).toEqual([]);
|
|
75
|
+
const rereadOrdered = saved.snapshot.pivotTables?.find(table => table.name === ordered.name);
|
|
76
|
+
expect(rereadOrdered?.fieldSettings?.map(entry => entry.field)).toEqual([4, 2]);
|
|
77
|
+
expect(formatWorkbookRange(rereadOrdered!.output)).toBe("A3:I6");
|
|
78
|
+
const rereadRanked = saved.snapshot.pivotTables?.find(table => table.name === ranked.name);
|
|
79
|
+
expect(rereadRanked?.fieldSettings).toContainEqual({ field: 2, sort: { direction: "desc", measure: 0 },
|
|
80
|
+
filter: { kind: "rank", measure: 0, order: "bottom", unit: "percent", count: 40 } });
|
|
81
|
+
expect(formatWorkbookRange(rereadRanked!.output)).toBe("A3:I10");
|
|
82
|
+
await workbook.undo("undo-native-value-settings");
|
|
83
|
+
expect(workbook.pivotTables().find(table => table.id === ordered.id)?.fieldSettings).toEqual(ordered.fieldSettings);
|
|
84
|
+
} finally { await workbook.close(); }
|
|
85
|
+
});
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { openWorkbook, parseWorkbookRange, workbookDateSerial, type WorkbookCommandCall, type WorkbookSession } from "@quirekit/workbook";
|
|
4
|
+
import { expect, it } from "vitest";
|
|
5
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
6
|
+
|
|
7
|
+
const fixture = new URL("../../../test/fixtures/native-pivot-member-groups.xlsx", import.meta.url);
|
|
8
|
+
|
|
9
|
+
/** @param workbook - Open session. @param commands - One atomic batch. @returns Published receipt. */
|
|
10
|
+
function edit(workbook: WorkbookSession, ...commands: WorkbookCommandCall[]) {
|
|
11
|
+
const baseRevision = workbook.revision;
|
|
12
|
+
return workbook.commit(workbook.prepare({ baseRevision, operationId: "member-group-" + baseRevision, commands }).id);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
it("loads different group aliases on two WPS reports that originally shared one native cache", () => {
|
|
16
|
+
const file = openXlsx("City members.xlsx", readFileSync(fixture));
|
|
17
|
+
expect(file.restrictions).toEqual([]);
|
|
18
|
+
const totals = file.snapshot.pivotTables?.find(table => table.name === "CityTotals");
|
|
19
|
+
const mirror = file.snapshot.pivotTables?.find(table => table.name === "CityMirror");
|
|
20
|
+
expect(totals).toMatchObject({ rowFields: [0], memberGroups: [{ field: 0, caption: "City2", groups: [
|
|
21
|
+
{ name: "South", members: ["Shenzhen", "Guangzhou"] }, { name: "East", members: ["Hangzhou", "Nanjing"] }
|
|
22
|
+
] }], cache: { fields: ["City", "Amount"] } });
|
|
23
|
+
expect(mirror?.memberGroups?.[0]?.groups.map(({ name }) => name)).toEqual(["数据组1", "数据组2"]);
|
|
24
|
+
expect(file.snapshot.sheets[1]!.cells).toEqual(expect.arrayContaining([
|
|
25
|
+
{ row: 1, column: 0, input: { kind: "value", value: "South" } },
|
|
26
|
+
{ row: 1, column: 7, input: { kind: "value", value: "数据组1" } },
|
|
27
|
+
{ row: 7, column: 9, input: { kind: "value", value: 635 } }
|
|
28
|
+
]));
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("preserves groups and raw source types through native export, refresh and reappearance of a configured member", async () => {
|
|
32
|
+
const file = openXlsx("City members.xlsx", readFileSync(fixture));
|
|
33
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
34
|
+
try {
|
|
35
|
+
const pivot = workbook.pivotTables().find(table => table.name === "CityTotals")!;
|
|
36
|
+
const report = pivot.output.sheetId, sales = pivot.source.sheetId;
|
|
37
|
+
const group = pivot.memberGroups![0]!;
|
|
38
|
+
const { field, caption, groups } = group;
|
|
39
|
+
const sourceCell = parseWorkbookRange(sales, "A3");
|
|
40
|
+
const target = parseWorkbookRange(report, "A1");
|
|
41
|
+
await edit(workbook, { name: "setPivotTable", target, params: {
|
|
42
|
+
id: pivot.id, name: pivot.name, source: { sheetId: sales, range: "A1:B8" }, rowFields: [0], columnFields: [],
|
|
43
|
+
memberGroups: [{ field, caption, groups, showMembers: false }], filters: [], values: pivot.values
|
|
44
|
+
} }, { name: "setCells", target: sourceCell, params: { value: "Suzhou" } },
|
|
45
|
+
{ name: "refreshPivotTable", target, params: { id: pivot.id } });
|
|
46
|
+
expect(workbook.readCell({ sheetId: report, row: 1, column: 1 }).input).toEqual({ kind: "value", value: 15 });
|
|
47
|
+
const bytes = file.write(workbook.snapshot());
|
|
48
|
+
const parts = unzipSync(bytes);
|
|
49
|
+
const caches = Object.keys(parts).filter(path => /^xl\/pivotCache\/pivotCacheDefinition\d+\.xml$/u.test(path));
|
|
50
|
+
const xml = caches.map(path => strFromU8(parts[path]!)).find(text => text.includes('v="Suzhou"'))!;
|
|
51
|
+
expect(xml).toContain('<discretePr count="7">');
|
|
52
|
+
expect(xml).toContain('<s v="Guangzhou"/>');
|
|
53
|
+
expect(xml).toContain('<s v="South"/>');
|
|
54
|
+
const reopened = openXlsx("Refreshed.xlsx", bytes);
|
|
55
|
+
expect(reopened.restrictions).toEqual([]);
|
|
56
|
+
const preserved = reopened.snapshot.pivotTables?.find(table => table.name === pivot.name)!;
|
|
57
|
+
expect(preserved.memberGroups).toMatchObject([{ field, caption, showMembers: false, groups: [
|
|
58
|
+
{ name: "South", members: ["Shenzhen", "Guangzhou"] }, { name: "East", members: ["Hangzhou", "Nanjing"] }
|
|
59
|
+
] }]);
|
|
60
|
+
expect(preserved.cache.records[1]).toEqual(["Suzhou", 20]);
|
|
61
|
+
|
|
62
|
+
const restored = await openWorkbook(reopened.snapshot, { appearance: reopened.appearance });
|
|
63
|
+
try {
|
|
64
|
+
await edit(restored, { name: "setCells", target: parseWorkbookRange(preserved.source.sheetId, "A3"), params: { value: "Guangzhou" } },
|
|
65
|
+
{ name: "refreshPivotTable", target: preserved.output, params: { id: preserved.id } });
|
|
66
|
+
expect(restored.readCell({ sheetId: preserved.output.sheetId, row: 1, column: 1 }).input).toEqual({ kind: "value", value: 35 });
|
|
67
|
+
expect(restored.readCell({ sheetId: preserved.output.sheetId, row: 5, column: 1 }).input).toEqual({ kind: "value", value: 635 });
|
|
68
|
+
} finally { await restored.close(); }
|
|
69
|
+
} finally { await workbook.close(); }
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it("roundtrips member groups on columns beside calendar rows and the Values label", async () => {
|
|
73
|
+
const november = workbookDateSerial(2026, 11, 1, "1900");
|
|
74
|
+
const rows = [["Booked", "City", "Amount"], [november, "Shenzhen", 10], [november + 1, "Guangzhou", 20],
|
|
75
|
+
[november + 30, "Beijing", 40]];
|
|
76
|
+
const workbook = await openWorkbook({ id: "calendar-cities", version: 1, revision: 0, name: "Calendar and cities", sheets: [
|
|
77
|
+
{ id: "sales", name: "Sales", cells: rows.flatMap((row, index) => row.map((value, column) => ({
|
|
78
|
+
row: index, column, input: { kind: "value", value }
|
|
79
|
+
}))), formats: rows.slice(1).map((_, index) => ({ row: index + 1, column: 0, format: { numberFormat: "yyyy-mm-dd" } })) },
|
|
80
|
+
{ id: "report", name: "Report", cells: [] }
|
|
81
|
+
] });
|
|
82
|
+
try {
|
|
83
|
+
const member = { field: 1, caption: "Market", groups: [{ name: "South", members: ["Shenzhen", "Guangzhou"] }] };
|
|
84
|
+
const valuesAxis = { axis: "column", position: 0 };
|
|
85
|
+
await edit(workbook, { name: "setPivotTable", target: parseWorkbookRange("report", "A1"), params: {
|
|
86
|
+
name: "CityDates", source: { sheetId: "sales", range: "A1:C4" }, rowFields: [0], columnFields: [1],
|
|
87
|
+
dateGroups: [{ field: 0, units: ["years", "months"] }], memberGroups: [member], filters: [], valuesAxis,
|
|
88
|
+
values: [{ field: 2, aggregate: "sum" }, { field: 2, aggregate: "count" }]
|
|
89
|
+
} });
|
|
90
|
+
const first = workbook.snapshot();
|
|
91
|
+
const reopened = openXlsx("Calendar and cities.xlsx", createXlsx(first));
|
|
92
|
+
expect(reopened.restrictions).toEqual([]);
|
|
93
|
+
expect(reopened.snapshot.pivotTables?.[0]).toMatchObject({
|
|
94
|
+
rowFields: [0], columnFields: [1], dateGroups: [{ field: 0, units: ["years", "months"] }],
|
|
95
|
+
memberGroups: [member], valuesAxis, cache: { records: rows.slice(1) }
|
|
96
|
+
});
|
|
97
|
+
expect(reopened.snapshot.sheets[1]!.cells).toEqual(first.sheets[1]!.cells);
|
|
98
|
+
} finally { await workbook.close(); }
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("retains the exact workbook when a discrete group index is out of bounds", () => {
|
|
102
|
+
const parts = unzipSync(readFileSync(fixture));
|
|
103
|
+
const path = "xl/pivotCache/pivotCacheDefinition1.xml";
|
|
104
|
+
const cache = strFromU8(parts[path]!);
|
|
105
|
+
const broken = cache.replace('<discretePr count="6"><x v="0"/>', '<discretePr count="6"><x v="6"/>');
|
|
106
|
+
expect(broken).not.toBe(cache);
|
|
107
|
+
parts[path] = strToU8(broken);
|
|
108
|
+
const bytes = zipSync(parts);
|
|
109
|
+
const file = openXlsx("Invalid member index.xlsx", bytes);
|
|
110
|
+
expect(file.restrictions).toContain("未支持的数据透视表、缓存或工作表关系");
|
|
111
|
+
expect(file.snapshot.pivotTables).toBeUndefined();
|
|
112
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("rebuilds the two levels of discrete grouping saved by WPS and writes their original-source mappings", async () => {
|
|
116
|
+
const fixture = new URL("../../../test/fixtures/native-pivot-nested-member-groups.xlsx", import.meta.url);
|
|
117
|
+
const file = openXlsx("Nested cities.xlsx", readFileSync(fixture));
|
|
118
|
+
expect(file.restrictions).toEqual([]);
|
|
119
|
+
const totals = file.snapshot.pivotTables?.find(table => table.name === "CityTotals")!;
|
|
120
|
+
const mirror = file.snapshot.pivotTables?.find(table => table.name === "CityMirror")!;
|
|
121
|
+
const coastal = { name: "数据组3", members: ["Shenzhen", "Guangzhou", "Hangzhou", "Nanjing"] };
|
|
122
|
+
expect(totals).toMatchObject({ rowFields: [0], memberGroups: [{ field: 0, caption: "City2", groups: [
|
|
123
|
+
{ name: "South", members: ["Shenzhen", "Guangzhou"] }, { name: "East", members: ["Hangzhou", "Nanjing"] }
|
|
124
|
+
], parents: [{ caption: "City3", groups: [coastal] }] }] });
|
|
125
|
+
expect(mirror.memberGroups?.[0]?.groups.map(({ name }) => name)).toEqual(["数据组1", "数据组2"]);
|
|
126
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
127
|
+
try {
|
|
128
|
+
const target = parseWorkbookRange(totals.output.sheetId, "A1");
|
|
129
|
+
await edit(workbook, { name: "setPivotItemExpanded", target,
|
|
130
|
+
params: { id: totals.id, field: 0, level: "members", memberLevel: 2, item: coastal.name, expanded: false } });
|
|
131
|
+
expect(workbook.readCell({ sheetId: target.sheetId, row: 1, column: 3 }).input).toEqual({ kind: "value", value: 155 });
|
|
132
|
+
const filter = { kind: "members", mode: "include", items: [coastal.name] };
|
|
133
|
+
await edit(workbook, { name: "setPivotFieldSettings", target,
|
|
134
|
+
params: { id: totals.id, field: 0, level: "members", memberLevel: 2, filter } });
|
|
135
|
+
expect(workbook.readCell({ sheetId: target.sheetId, row: 2, column: 3 }).input).toEqual({ kind: "value", value: 155 });
|
|
136
|
+
const bytes = file.write(workbook.snapshot());
|
|
137
|
+
const parts = unzipSync(bytes);
|
|
138
|
+
const xml = Object.keys(parts).filter(path => /^xl\/pivotCache\/pivotCacheDefinition\d+\.xml$/u.test(path))
|
|
139
|
+
.map(path => strFromU8(parts[path]!)).find(xml => xml.includes("City3"))!;
|
|
140
|
+
expect(xml).toContain('<fieldGroup par="2"/>');
|
|
141
|
+
expect(xml).toMatch(/<fieldGroup (?:base="0" par="3"|par="3" base="0")>/u);
|
|
142
|
+
const reopened = openXlsx("Collapsed cities.xlsx", bytes);
|
|
143
|
+
expect(reopened.restrictions).toEqual([]);
|
|
144
|
+
expect(reopened.snapshot.pivotTables?.find(table => table.name === totals.name)).toMatchObject({
|
|
145
|
+
memberGroups: totals.memberGroups, collapsedItems: [{ field: 0, level: "members", memberLevel: 2, items: [coastal.name] }],
|
|
146
|
+
fieldSettings: [{ field: 0, level: "members", memberLevel: 2, filter }]
|
|
147
|
+
});
|
|
148
|
+
expect(reopened.snapshot.sheets[1]!.cells).toEqual(workbook.snapshot().sheets[1]!.cells);
|
|
149
|
+
} finally { await workbook.close(); }
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it.each([
|
|
153
|
+
['<fieldGroup base="0"><discretePr', '<fieldGroup base="0" par="2"><discretePr'],
|
|
154
|
+
['<discretePr count="6"><x v="0"/><x v="0"/><x v="0"/>', '<discretePr count="6"><x v="1"/><x v="0"/><x v="0"/>']
|
|
155
|
+
] as const)("preserves the original XLSX when a higher grouping link or allocation is invalid", (before, after) => {
|
|
156
|
+
const fixture = new URL("../../../test/fixtures/native-pivot-nested-member-groups.xlsx", import.meta.url);
|
|
157
|
+
const parts = unzipSync(readFileSync(fixture));
|
|
158
|
+
const path = "xl/pivotCache/pivotCacheDefinition1.xml";
|
|
159
|
+
const cache = strFromU8(parts[path]!);
|
|
160
|
+
const broken = cache.replace(before, after);
|
|
161
|
+
expect(broken).not.toBe(cache);
|
|
162
|
+
parts[path] = strToU8(broken);
|
|
163
|
+
const bytes = zipSync(parts);
|
|
164
|
+
const file = openXlsx("Broken grouping hierarchy.xlsx", bytes);
|
|
165
|
+
expect(file.restrictions).toContain("未支持的数据透视表、缓存或工作表关系");
|
|
166
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
167
|
+
});
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { openWorkbook, parseWorkbookRange, workbookDateSerial, type WorkbookCommandCall, type WorkbookSession } from "@quirekit/workbook";
|
|
4
|
+
import { expect, it } from "vitest";
|
|
5
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
6
|
+
|
|
7
|
+
const automaticFixture = new URL("../../../test/fixtures/native-pivot-number-groups.xlsx", import.meta.url);
|
|
8
|
+
const fixedFixture = new URL("../../../test/fixtures/native-pivot-number-bounds.xlsx", import.meta.url);
|
|
9
|
+
|
|
10
|
+
/** @param workbook - Current workbook. @param commands - Edits from one revision. @returns Published changes. */
|
|
11
|
+
function edit(workbook: WorkbookSession, ...commands: WorkbookCommandCall[]) {
|
|
12
|
+
const baseRevision = workbook.revision;
|
|
13
|
+
return workbook.commit(workbook.prepare({ baseRevision, operationId: "numeric-pivot-" + baseRevision, commands }).id);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** @param workbook - Current workbook. @param name - PivotTable name. @returns Its visible groups and sum through the grand total. */
|
|
17
|
+
function result(workbook: WorkbookSession, name: string) {
|
|
18
|
+
const { sheetId, startRow, startColumn, endRow } = workbook.pivotTables().find(table => table.name === name)!.output;
|
|
19
|
+
return Array.from({ length: endRow - startRow }, (_, index) => [startColumn, startColumn + 1].map(column => {
|
|
20
|
+
const input = workbook.readCell({ sheetId, row: startRow + index + 1, column }).input;
|
|
21
|
+
return input?.kind === "value" ? input.value : undefined;
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
it("uses each WPS report's active group from a shared cache and retains exact integer and decimal members", async () => {
|
|
26
|
+
const file = openXlsx("Bounded intervals.xlsx", readFileSync(fixedFixture));
|
|
27
|
+
expect(file.restrictions).toEqual([]);
|
|
28
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
29
|
+
try {
|
|
30
|
+
const decimal = workbook.pivotTables().find(table => table.name === "DecimalBands");
|
|
31
|
+
const integer = workbook.pivotTables().find(table => table.name === "IntegerBands");
|
|
32
|
+
expect(decimal).toMatchObject({ name: "DecimalBands", rowFields: [0],
|
|
33
|
+
numberGroups: [{ field: 0, interval: 1, start: -2, end: 2 }] });
|
|
34
|
+
expect(integer).toMatchObject({ name: "IntegerBands", rowFields: [2],
|
|
35
|
+
numberGroups: [{ field: 2, interval: 2, start: -2, end: 4 }] });
|
|
36
|
+
expect(result(workbook, "DecimalBands")).toEqual([
|
|
37
|
+
["<-2", 1], ["-2--1", 2], ["-1-0", 12], ["0-1", 48], ["1-2", 448], [">2", 1536], ["总计", 2047]
|
|
38
|
+
]);
|
|
39
|
+
expect(result(workbook, "IntegerBands")).toEqual([
|
|
40
|
+
["<-2", 1], ["-2--1", 6], ["0-1", 24], ["2-4", 224], [">4", 1792], ["总计", 2047]
|
|
41
|
+
]);
|
|
42
|
+
} finally { await workbook.close(); }
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("recalculates automatic bounds on refresh and writes native intervals without changing the shared source values", async () => {
|
|
46
|
+
const file = openXlsx("Automatic intervals.xlsx", readFileSync(automaticFixture));
|
|
47
|
+
expect(file.restrictions).toEqual([]);
|
|
48
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
49
|
+
try {
|
|
50
|
+
const table = workbook.pivotTables().find(pivot => pivot.name === "DecimalBands")!;
|
|
51
|
+
expect(table.numberGroups).toMatchObject([{ field: 0, interval: 0.5, labels: { start: -3, end: 3 } }]);
|
|
52
|
+
expect(table.numberGroups?.[0]?.end).toBeUndefined();
|
|
53
|
+
expect(result(workbook, "DecimalBands").at(-2)).toEqual(["2.5-3", 1536]);
|
|
54
|
+
await edit(workbook, { name: "setCells", target: parseWorkbookRange(table.source.sheetId, "A12"), params: { value: 4 } },
|
|
55
|
+
{ name: "refreshPivotTable", target: table.output, params: { id: table.id } });
|
|
56
|
+
expect(result(workbook, "DecimalBands").slice(-3).map(row => row[1])).toEqual([512, 1024, 2047]);
|
|
57
|
+
const bytes = file.write(workbook.snapshot());
|
|
58
|
+
const reopened = openXlsx("Refreshed.xlsx", bytes);
|
|
59
|
+
expect(reopened.restrictions).toEqual([]);
|
|
60
|
+
const decimal = reopened.snapshot.pivotTables?.find(pivot => pivot.name === "DecimalBands");
|
|
61
|
+
const integer = reopened.snapshot.pivotTables?.find(pivot => pivot.name === "IntegerBands");
|
|
62
|
+
expect(decimal?.numberGroups).toMatchObject([{ field: 0, interval: 0.5, labels: { start: -3, end: 4 } }]);
|
|
63
|
+
expect(decimal?.numberGroups?.[0]?.end).toBeUndefined();
|
|
64
|
+
expect(decimal?.cache.records.at(-1)).toEqual([4, 1024, 7]);
|
|
65
|
+
expect(integer?.cache.records.at(-1)).toEqual([3, 1024, 7]);
|
|
66
|
+
expect(integer?.numberGroups).toMatchObject([{ field: 2, interval: 2, start: -2, end: 4 }]);
|
|
67
|
+
expect(reopened.snapshot.sheets[0]!.cells).toEqual(expect.arrayContaining([
|
|
68
|
+
{ row: 11, column: 5, input: { kind: "value", value: 1024 } },
|
|
69
|
+
{ row: 12, column: 5, input: { kind: "value", value: 2047 } },
|
|
70
|
+
{ row: 6, column: 10, input: { kind: "value", value: 2047 } }
|
|
71
|
+
]));
|
|
72
|
+
} finally { await workbook.close(); }
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("writes numeric column groups beside expanded dates and sums the raw values of the grouped field", async () => {
|
|
76
|
+
const day = workbookDateSerial(2026, 11, 3, "1900");
|
|
77
|
+
const rows = [["Date", "Score"], [day, -2], [day, 0], [day + 31, 1], [day + 31, 2]];
|
|
78
|
+
const workbook = await openWorkbook({ id: "groups", version: 1, revision: 0, name: "Calendar and intervals", sheets: [
|
|
79
|
+
{ id: "sales", name: "Sales", cells: rows.flatMap((row, index) => row.map((value, column) => ({
|
|
80
|
+
row: index, column, input: { kind: "value", value }
|
|
81
|
+
}))), formats: rows.slice(1).map((_, index) => ({
|
|
82
|
+
row: index + 1, column: 0, format: { numberFormat: "yyyy-mm-dd" }
|
|
83
|
+
})) },
|
|
84
|
+
{ id: "report", name: "Report", cells: [] }
|
|
85
|
+
] });
|
|
86
|
+
try {
|
|
87
|
+
const group = { field: 1, interval: 1.5, start: -2, end: 2 };
|
|
88
|
+
await edit(workbook, { name: "setPivotTable", target: parseWorkbookRange("report", "A1"), params: {
|
|
89
|
+
name: "MixedGroups", source: { sheetId: "sales", range: "A1:B5" }, rowFields: [0], columnFields: [1],
|
|
90
|
+
dateGroups: [{ field: 0, units: ["years", "months"] }], numberGroups: [group], filters: [],
|
|
91
|
+
values: [{ field: 1, aggregate: "sum" }]
|
|
92
|
+
} });
|
|
93
|
+
const bytes = createXlsx(workbook.snapshot());
|
|
94
|
+
const parts = unzipSync(bytes);
|
|
95
|
+
const cache = strFromU8(parts["xl/pivotCache/pivotCacheDefinition1.xml"]!);
|
|
96
|
+
expect(cache).toMatch(/<rangePr[^>]+groupBy="range"[^>]+startNum="-2"[^>]+endNum="2"[^>]+groupInterval="1\.5"/u);
|
|
97
|
+
expect(cache).toContain("<n v=\"-2\"/>");
|
|
98
|
+
const reopened = openXlsx("Mixed groups.xlsx", bytes);
|
|
99
|
+
expect(reopened.restrictions).toEqual([]);
|
|
100
|
+
const table = reopened.snapshot.pivotTables?.[0];
|
|
101
|
+
expect(table).toMatchObject({ rowFields: [0], columnFields: [1], dateGroups: [{ field: 0, units: ["years", "months"] }],
|
|
102
|
+
numberGroups: [group], cache: { records: rows.slice(1) } });
|
|
103
|
+
expect(reopened.snapshot.sheets[1]!.cells).toContainEqual({
|
|
104
|
+
row: table!.output.endRow, column: table!.output.endColumn, input: { kind: "value", value: 1 }
|
|
105
|
+
});
|
|
106
|
+
} finally { await workbook.close(); }
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("preserves the original XLSX when its native numeric interval cannot describe the group items", () => {
|
|
110
|
+
const parts = unzipSync(readFileSync(automaticFixture));
|
|
111
|
+
const path = "xl/pivotCache/pivotCacheDefinition1.xml";
|
|
112
|
+
const cache = strFromU8(parts[path]!);
|
|
113
|
+
expect(cache).toContain('groupInterval="0.5"');
|
|
114
|
+
parts[path] = strToU8(cache.replace('groupInterval="0.5"', 'groupInterval="0"'));
|
|
115
|
+
const bytes = zipSync(parts);
|
|
116
|
+
const file = openXlsx("Invalid interval.xlsx", bytes);
|
|
117
|
+
expect(file.restrictions).toContain("未支持的数据透视表、缓存或工作表关系");
|
|
118
|
+
expect(file.snapshot.pivotTables).toBeUndefined();
|
|
119
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
120
|
+
});
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { createWorkbookPivotStore, type WorkbookAppearance, type WorkbookPivotTable, type WorkbookSession, type WorkbookWorksheetIdentity } from "@quirekit/workbook";
|
|
3
|
+
import { readRelationships, relationshipsPath } from "../../opc/relationships";
|
|
4
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
|
|
5
|
+
import type { PackageRelationship } from "../../opc/types";
|
|
6
|
+
import { child, parsePart, readIndex, relationshipNs, rootOf, spreadNs } from "../../opc/xml";
|
|
7
|
+
import { readXlsxPivotCache } from "../cache/read";
|
|
8
|
+
import { readXlsxPivotDefinition } from "../definition/read";
|
|
9
|
+
import type { XlsxPivotCache, XlsxPivotGraph } from "../types";
|
|
10
|
+
import { pivotContentTypes, pivotMembers, pivotRoles } from "../xml";
|
|
11
|
+
import { verifyXlsxPartOwnership } from "../../opc/ownership";
|
|
12
|
+
|
|
13
|
+
/** @param archive - Source ZIP parts. @param workbook - Workbook element. @param path - Workbook part.
|
|
14
|
+
* @param relationships - Relationships owned by the workbook. @param sheets - Directory with stable worksheet IDs.
|
|
15
|
+
* @param sheetPaths - Native part by sheet ID. @param dateSystem - Workbook calendar.
|
|
16
|
+
* @param appearance - Native worksheet styles available for resolving clock caches.
|
|
17
|
+
* @param restrictions - Reasons to preserve the original.
|
|
18
|
+
* @returns Supported native PivotTables and their ownership. */
|
|
19
|
+
export function readXlsxPivotPackage(archive: Readonly<Record<string, Uint8Array>>, workbook: Element, path: string,
|
|
20
|
+
relationships: ReadonlyMap<string, PackageRelationship>, sheets: readonly WorkbookWorksheetIdentity[],
|
|
21
|
+
sheetPaths: ReadonlyMap<string, string>, dateSystem: WorkbookSession["dateSystem"],
|
|
22
|
+
appearance: WorkbookAppearance, restrictions: Set<string>): { tables: readonly WorkbookPivotTable[]; graph?: XlsxPivotGraph } {
|
|
23
|
+
const workbookRelations = new Set<string>();
|
|
24
|
+
const worksheetRelations = new Map<string, Set<string>>();
|
|
25
|
+
const ownedParts = new Set<string>();
|
|
26
|
+
const owners = new Map<string, Set<string>>();
|
|
27
|
+
const types = new Map<string, string>();
|
|
28
|
+
const caches = new Map<number, { data: XlsxPivotCache; path: string }>();
|
|
29
|
+
const names = new Map(sheets.map(sheet => [sheet.name.toUpperCase(), sheet.id]));
|
|
30
|
+
const usedCaches = new Set<number>();
|
|
31
|
+
const tables: WorkbookPivotTable[] = [];
|
|
32
|
+
const cacheList = child(workbook, "pivotCaches");
|
|
33
|
+
const nativeCaches = [...relationships.values()].filter(relation => relation.type === pivotRoles.cache);
|
|
34
|
+
try {
|
|
35
|
+
/** @param part - Related native part. @param owner - Parent part. @param type - Content type required to rewrite it. */
|
|
36
|
+
function own(part: string, owner: string, type: string): void {
|
|
37
|
+
const by = owners.get(part) ?? new Set<string>();
|
|
38
|
+
if (by.has(owner) || types.has(part) && types.get(part) !== type) throw new Error("数据透视表部件所有权不唯一。");
|
|
39
|
+
by.add(owner);
|
|
40
|
+
owners.set(part, by);
|
|
41
|
+
types.set(part, type);
|
|
42
|
+
ownedParts.add(part);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
for (const entry of pivotMembers(cacheList, "pivotCache")) {
|
|
46
|
+
const id = readIndex(entry, "cacheId");
|
|
47
|
+
const relation = relationships.get(entry.getAttributeNS(relationshipNs, "id") ?? "");
|
|
48
|
+
if (id === undefined || caches.has(id) || !relation?.path || relation.type !== pivotRoles.cache
|
|
49
|
+
|| !hasKnownAttributes(entry, ["cacheId"], true) || !hasKnownChildren(entry, [])) throw new Error("数据透视表缓存关系无效。");
|
|
50
|
+
const retained = readXlsxPivotCache(archive, relation.path, names, dateSystem, appearance);
|
|
51
|
+
own(relation.path, path, pivotContentTypes.cache);
|
|
52
|
+
own(retained.recordPart, relation.path, pivotContentTypes.records);
|
|
53
|
+
ownedParts.add(relationshipsPath(relation.path));
|
|
54
|
+
caches.set(id, { data: retained.data, path: relation.path });
|
|
55
|
+
workbookRelations.add(relation.id);
|
|
56
|
+
}
|
|
57
|
+
if (workbookRelations.size !== nativeCaches.length) throw new Error("数据透视表缓存未登记在工作簿目录中。");
|
|
58
|
+
|
|
59
|
+
for (const [sheetId, sheetPath] of sheetPaths) {
|
|
60
|
+
const sheetLinks = relationshipsPath(sheetPath);
|
|
61
|
+
if (!archive[sheetLinks]) continue;
|
|
62
|
+
const links = readRelationships(parsePart(archive[sheetLinks], sheetLinks), sheetPath);
|
|
63
|
+
for (const relation of links.values()) {
|
|
64
|
+
if (relation.type !== pivotRoles.definition) continue;
|
|
65
|
+
if (!relation.path || owners.has(relation.path)) throw new Error("工作表的数据透视表关系无效。");
|
|
66
|
+
const definition = rootOf(parsePart(archive[relation.path], relation.path), spreadNs, "pivotTableDefinition");
|
|
67
|
+
const id = readIndex(definition, "cacheId");
|
|
68
|
+
const cache = id === undefined ? undefined : caches.get(id);
|
|
69
|
+
const partRels = relationshipsPath(relation.path);
|
|
70
|
+
const pivotLinks = readRelationships(parsePart(archive[partRels], partRels), relation.path);
|
|
71
|
+
const pivotCache = [...pivotLinks.values()][0];
|
|
72
|
+
if (!cache || pivotLinks.size !== 1 || pivotCache?.path !== cache.path || pivotCache.type !== pivotRoles.cache) {
|
|
73
|
+
throw new Error("透视表定义与工作簿缓存不一致。");
|
|
74
|
+
}
|
|
75
|
+
own(relation.path, sheetPath, pivotContentTypes.definition);
|
|
76
|
+
own(cache.path, relation.path, pivotContentTypes.cache);
|
|
77
|
+
ownedParts.add(partRels);
|
|
78
|
+
usedCaches.add(id!);
|
|
79
|
+
tables.push(readXlsxPivotDefinition(definition, sheetId, cache.data));
|
|
80
|
+
const managed = worksheetRelations.get(sheetPath) ?? new Set<string>();
|
|
81
|
+
managed.add(relation.id);
|
|
82
|
+
worksheetRelations.set(sheetPath, managed);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (usedCaches.size !== caches.size) throw new Error("存在未关联到工作表的数据透视表缓存。");
|
|
86
|
+
if (!tables.length) return { tables: [] };
|
|
87
|
+
verifyXlsxPartOwnership(archive, owners, types);
|
|
88
|
+
return { tables: createWorkbookPivotStore(tables, sheets).list(), graph: { workbookRelations, worksheetRelations, parts: ownedParts } };
|
|
89
|
+
} catch {
|
|
90
|
+
restrictions.add("未支持的数据透视表、缓存或工作表关系");
|
|
91
|
+
return { tables: [] };
|
|
92
|
+
}
|
|
93
|
+
}
|