@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,244 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { openWorkbook, parseWorkbookRange, type WorkbookCommandCall, type WorkbookPivotValuesAxis, type WorkbookSession, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
4
|
+
import { describe, expect, it } from "vitest";
|
|
5
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
6
|
+
|
|
7
|
+
const data = [
|
|
8
|
+
["地区", "状态", "金额", "渠道"],
|
|
9
|
+
["华南", "未结", 500, "直营"],
|
|
10
|
+
["华东", "结清", 170, "代理"],
|
|
11
|
+
["华南", "结清", 400, "直营"],
|
|
12
|
+
["华东", "未结", 300, "直营"],
|
|
13
|
+
["华东", "未结", 100, "直营"]
|
|
14
|
+
];
|
|
15
|
+
const seed: WorkbookSnapshot = { id: "ledger", version: 1, revision: 0, name: "回款表", dateSystem: "1900", sheets: [
|
|
16
|
+
{ id: "orders", name: "订单", cells: data.flatMap((record, row) => record.map((value, column) => ({ row, column, input: { kind: "value", value } }))) },
|
|
17
|
+
{ id: "report", name: "报表", cells: [] }
|
|
18
|
+
] };
|
|
19
|
+
|
|
20
|
+
/** @param workbook - Current workbook. @param commands - Requested changes. @returns The committed receipt. */
|
|
21
|
+
function edit(workbook: WorkbookSession, ...commands: WorkbookCommandCall[]) {
|
|
22
|
+
const baseRevision = workbook.revision;
|
|
23
|
+
return workbook.commit(workbook.prepare({ baseRevision, operationId: "pivot-" + baseRevision, commands }).id);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param valuesAxis - Optional placement preference. @returns An authored native PivotTable and standard XLSX bytes. */
|
|
27
|
+
async function fixture(valuesAxis?: WorkbookPivotValuesAxis): Promise<Uint8Array> {
|
|
28
|
+
const workbook = await openWorkbook(seed);
|
|
29
|
+
try {
|
|
30
|
+
await edit(workbook, { name: "setPivotTable", target: parseWorkbookRange("report", "B3"),
|
|
31
|
+
params: { name: "回款透视表", source: { sheetId: "orders", range: "A1:D6" }, rowFields: [0], columnFields: [1],
|
|
32
|
+
filters: [{ field: 3, equals: "直营" }], values: [{ field: 2, aggregate: "sum" }, { field: 2, aggregate: "countNumbers" }],
|
|
33
|
+
...(valuesAxis && { valuesAxis }) } });
|
|
34
|
+
return createXlsx(workbook.snapshot());
|
|
35
|
+
} finally { await workbook.close(); }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
describe("editable native PivotTable parts", () => {
|
|
39
|
+
it("reopens a local region with ordered axes, typed cache, measures, filters and materialized results", async () => {
|
|
40
|
+
const bytes = await fixture();
|
|
41
|
+
const parts = unzipSync(bytes);
|
|
42
|
+
const definition = Object.keys(parts).find(path => /^xl\/pivotTables\/pivotTable\d+\.xml$/u.test(path))!;
|
|
43
|
+
expect(strFromU8(parts[definition]!)).toContain('subtotal="countNums"');
|
|
44
|
+
expect(strFromU8(parts["xl/worksheets/_rels/sheet2.xml.rels"]!)).toContain("/pivotTable");
|
|
45
|
+
const file = openXlsx("回款", bytes);
|
|
46
|
+
expect(file.restrictions).toEqual([]);
|
|
47
|
+
const report = file.snapshot.sheets[1]!;
|
|
48
|
+
const table = file.snapshot.pivotTables?.[0];
|
|
49
|
+
expect(table).toMatchObject({ name: "回款透视表", source: parseWorkbookRange(file.snapshot.sheets[0]!.id, "A1:D6"),
|
|
50
|
+
output: parseWorkbookRange(report.id, "B3:H10"), cache: { fields: data[0], records: data.slice(1) },
|
|
51
|
+
rowFields: [0], columnFields: [1], filters: [{ field: 3, equals: "直营" }],
|
|
52
|
+
values: [{ field: 2, aggregate: "sum" }, { field: 2, aggregate: "countNumbers" }] });
|
|
53
|
+
expect(report.cells).toContainEqual({ row: 9, column: 6, input: { kind: "value", value: 1300 } });
|
|
54
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("writes the prefix and measure ordinal for each native subtotal column and reopens the result", async () => {
|
|
58
|
+
const workbook = await openWorkbook(seed);
|
|
59
|
+
try {
|
|
60
|
+
await edit(workbook, { name: "setPivotTable", target: parseWorkbookRange("report", "A1"),
|
|
61
|
+
params: { name: "渠道小计", source: { sheetId: "orders", range: "A1:D6" }, rowFields: [0], columnFields: [3, 1],
|
|
62
|
+
filters: [], values: [{ field: 2, aggregate: "sum" }, { field: 2, aggregate: "stdevp" }],
|
|
63
|
+
subtotals: [{ field: 3, aggregate: "average" }] } });
|
|
64
|
+
const bytes = createXlsx(workbook.snapshot());
|
|
65
|
+
const parts = unzipSync(bytes);
|
|
66
|
+
const definition = Object.keys(parts).find(path => /^xl\/pivotTables\/pivotTable\d+\.xml$/u.test(path))!;
|
|
67
|
+
const xml = strFromU8(parts[definition]!);
|
|
68
|
+
expect(xml).toMatch(/<pivotField axis="axisCol"[^>]+outline="0"/u);
|
|
69
|
+
expect(xml).toContain('avgSubtotal="1"');
|
|
70
|
+
expect(xml).toContain('<item t="avg"/>');
|
|
71
|
+
expect(xml).toContain('<i t="avg" i="1"><x v="0"/></i>');
|
|
72
|
+
expect(xml).toContain('subtotal="stdDevp"');
|
|
73
|
+
const file = openXlsx("渠道小计", bytes);
|
|
74
|
+
expect(file.restrictions).toEqual([]);
|
|
75
|
+
expect(file.snapshot.pivotTables?.[0]).toMatchObject({
|
|
76
|
+
subtotals: [{ field: 3, aggregate: "average" }], values: [{ field: 2, aggregate: "sum" }, { field: 2, aggregate: "stdevp" }]
|
|
77
|
+
});
|
|
78
|
+
expect(file.snapshot.sheets[1]!.cells).toEqual(expect.arrayContaining(
|
|
79
|
+
[5, 6].map(column => ({ row: 4, column, input: { kind: "value", value: 450 } }))
|
|
80
|
+
));
|
|
81
|
+
} finally { await workbook.close(); }
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it.each([
|
|
85
|
+
{ axis: "row", position: 0, tag: "rowFields", members: [-2, 0], cell: { row: 10, column: 5 } },
|
|
86
|
+
{ axis: "row", position: 1, tag: "rowFields", members: [0, -2], cell: { row: 10, column: 5 } },
|
|
87
|
+
{ axis: "column", position: 0, tag: "colFields", members: [-2, 1], cell: { row: 9, column: 6 } }
|
|
88
|
+
] as const)("writes and reopens native Values placement $axis/$position", async ({ axis, position, tag, members, cell }) => {
|
|
89
|
+
const valuesAxis = { axis, position };
|
|
90
|
+
const parts = unzipSync(await fixture(valuesAxis));
|
|
91
|
+
const path = Object.keys(parts).find(part => /^xl\/pivotTables\/pivotTable\d+\.xml$/u.test(part))!;
|
|
92
|
+
const xml = strFromU8(parts[path]!);
|
|
93
|
+
expect(xml).toContain(`<${tag} count="2">${members.map(field => `<field x="${field}"/>`).join("")}</${tag}>`);
|
|
94
|
+
expect(xml).toContain(`dataPosition="${position}"`);
|
|
95
|
+
if (axis === "row") expect(xml).toContain('dataOnRows="1"');
|
|
96
|
+
|
|
97
|
+
// Spreadsheet producers may rely on the ordinal carried by the marker and the final total block.
|
|
98
|
+
const normalized = (position === 0 ? xml.replace(' dataPosition="0"', "") : xml).replaceAll('<i t="grand" i="1">', '<i t="grand">');
|
|
99
|
+
parts[path] = strToU8(normalized);
|
|
100
|
+
const reopened = openXlsx("回款指标", zipSync(parts));
|
|
101
|
+
expect(reopened.restrictions).toEqual([]);
|
|
102
|
+
expect(reopened.snapshot.pivotTables?.[0]).toMatchObject({ valuesAxis, rowFields: [0], columnFields: [1],
|
|
103
|
+
values: [{ field: 2, aggregate: "sum" }, { field: 2, aggregate: "countNumbers" }] });
|
|
104
|
+
expect(reopened.snapshot.sheets[1]?.cells).toContainEqual({ ...cell, input: { kind: "value", value: 1300 } });
|
|
105
|
+
|
|
106
|
+
const mismatched = normalized.replace('x="-2"', 'x="127"');
|
|
107
|
+
parts[path] = strToU8(mismatched);
|
|
108
|
+
const original = zipSync(parts);
|
|
109
|
+
const protectedFile = openXlsx("值字段位置冲突", original);
|
|
110
|
+
expect(protectedFile.snapshot.pivotTables).toBeUndefined();
|
|
111
|
+
expect(protectedFile.write(protectedFile.snapshot)).toEqual(original);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("refreshes the measure-first rows of a WPS export with repeated prefixes", async () => {
|
|
115
|
+
const path = new URL("../../../test/fixtures/native-pivot-values-rows.xlsx", import.meta.url);
|
|
116
|
+
const file = openXlsx("WPS values rows", readFileSync(path));
|
|
117
|
+
expect(file.restrictions).toEqual([]);
|
|
118
|
+
const workbook = await openWorkbook(file.snapshot);
|
|
119
|
+
try {
|
|
120
|
+
const table = workbook.pivotTables()[0]!;
|
|
121
|
+
const valuesAxis = { axis: "row", position: 0 };
|
|
122
|
+
expect(table).toMatchObject({ valuesAxis, rowFields: [0], values: [{ field: 2, aggregate: "sum" }, { field: 1, aggregate: "sum" }] });
|
|
123
|
+
await edit(workbook, { name: "setCells", target: parseWorkbookRange(table.source.sheetId, "C2"),
|
|
124
|
+
params: { cells: [[{ kind: "value", value: 260 }]] } },
|
|
125
|
+
{ name: "refreshPivotTable", target: table.output, params: { id: table.id } });
|
|
126
|
+
const reopened = openXlsx("WPS values refreshed", file.write(workbook.snapshot()));
|
|
127
|
+
expect(reopened.restrictions).toEqual([]);
|
|
128
|
+
expect(reopened.snapshot.pivotTables?.[0]?.valuesAxis).toEqual(valuesAxis);
|
|
129
|
+
expect(reopened.snapshot.sheets[1]?.cells).toEqual(expect.arrayContaining([
|
|
130
|
+
{ row: 9, column: 2, input: { kind: "value", value: 510 } },
|
|
131
|
+
{ row: 10, column: 2, input: { kind: "value", value: 250 } }
|
|
132
|
+
]));
|
|
133
|
+
} finally { await workbook.close(); }
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("saves a native drill-through table and keeps the disabled detail option in the original pivot", async () => {
|
|
137
|
+
const file = openXlsx("明细", await fixture());
|
|
138
|
+
const workbook = await openWorkbook(file.snapshot);
|
|
139
|
+
try {
|
|
140
|
+
const [table] = workbook.pivotTables();
|
|
141
|
+
const target = parseWorkbookRange(table!.output.sheetId, "C8");
|
|
142
|
+
await edit(workbook, { name: "showPivotDetails", target, params: { id: table!.id, name: "华南未结" } });
|
|
143
|
+
const [detail] = workbook.snapshot().structuredTables ?? [];
|
|
144
|
+
expect(detail?.range).toMatchObject({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 3 });
|
|
145
|
+
await edit(workbook, { name: "setPivotTable", target: parseWorkbookRange(table!.output.sheetId, "B3"), params: {
|
|
146
|
+
id: table!.id, name: table!.name, source: { sheetId: table!.source.sheetId, range: "A1:D6" },
|
|
147
|
+
rowFields: table!.rowFields, columnFields: table!.columnFields, values: table!.values, filters: table!.filters, showDetails: false
|
|
148
|
+
} });
|
|
149
|
+
const serialized = file.write(workbook.snapshot());
|
|
150
|
+
const parts = unzipSync(serialized);
|
|
151
|
+
const pivot = Object.keys(parts).find(path => /^xl\/pivotTables\/pivotTable\d+\.xml$/u.test(path))!;
|
|
152
|
+
expect(strFromU8(parts[pivot]!)).toContain('enableDrill="0"');
|
|
153
|
+
const reopened = openXlsx("华南未结", serialized);
|
|
154
|
+
expect(reopened.restrictions).toEqual([]);
|
|
155
|
+
expect(reopened.snapshot.pivotTables?.[0]?.showDetails).toBe(false);
|
|
156
|
+
const detailSheet = reopened.snapshot.sheets.find(sheet => sheet.name === "华南未结")!;
|
|
157
|
+
expect(reopened.snapshot.structuredTables?.[0]).toMatchObject({ range: parseWorkbookRange(detailSheet.id, "A1:D2"), showFilter: true });
|
|
158
|
+
expect(detailSheet.cells).toContainEqual({ row: 1, column: 2, input: { kind: "value", value: 500 } });
|
|
159
|
+
} finally { await workbook.close(); }
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("removes the owned graph after deleting the result and preserves the source sheet", async () => {
|
|
163
|
+
const bytes = await fixture();
|
|
164
|
+
const file = openXlsx("回款", bytes);
|
|
165
|
+
const workbook = await openWorkbook(file.snapshot);
|
|
166
|
+
try {
|
|
167
|
+
const pivot = workbook.pivotTables()[0]!;
|
|
168
|
+
await edit(workbook, { name: "deletePivotTable", target: pivot.output, params: { id: pivot.id } });
|
|
169
|
+
const saved = file.write(workbook.snapshot());
|
|
170
|
+
const parts = unzipSync(saved);
|
|
171
|
+
expect(Object.keys(parts).filter(path => /pivot/iu.test(path))).toEqual([]);
|
|
172
|
+
expect(parts["xl/worksheets/sheet1.xml"]).toEqual(unzipSync(bytes)["xl/worksheets/sheet1.xml"]);
|
|
173
|
+
expect(openXlsx("回款", saved).snapshot.pivotTables).toBeUndefined();
|
|
174
|
+
} finally { await workbook.close(); }
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("opens producer-normalized value positions without discarding the calculation version signature", async () => {
|
|
178
|
+
const parts = unzipSync(await fixture());
|
|
179
|
+
const path = Object.keys(parts).find(part => /^xl\/pivotTables\/pivotTable\d+\.xml$/u.test(part))!;
|
|
180
|
+
parts[path] = strToU8(strFromU8(parts[path]!).replace('cacheId="1"', 'cacheId="1" dataPosition="1"')
|
|
181
|
+
.replace('axis="axisPage"', 'axis="axisPage" multipleItemSelectionAllowed="1"'));
|
|
182
|
+
const workbookPath = "xl/workbook.xml";
|
|
183
|
+
const extension = '<extLst><ext uri="{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}">'
|
|
184
|
+
+ '<calcFeatures xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures"><feature name="microsoft.com:Single"/></calcFeatures></ext></extLst>';
|
|
185
|
+
parts[workbookPath] = strToU8(strFromU8(parts[workbookPath]!).replace("</workbook>", extension + "</workbook>"));
|
|
186
|
+
const file = openXlsx("回款", zipSync(parts));
|
|
187
|
+
expect(file.restrictions).toEqual([]);
|
|
188
|
+
const workbook = await openWorkbook(file.snapshot);
|
|
189
|
+
try {
|
|
190
|
+
const pivot = workbook.pivotTables()[0]!;
|
|
191
|
+
await edit(workbook, { name: "setCells", target: parseWorkbookRange(pivot.source.sheetId, "C2"), params: { cells: [[{ kind: "value", value: 600 }]] } },
|
|
192
|
+
{ name: "refreshPivotTable", target: pivot.output, params: { id: pivot.id } });
|
|
193
|
+
const bytes = file.write(workbook.snapshot());
|
|
194
|
+
expect(strFromU8(unzipSync(bytes)[workbookPath]!)).toContain(extension);
|
|
195
|
+
const reopened = openXlsx("回款", bytes);
|
|
196
|
+
expect(reopened.restrictions).toEqual([]);
|
|
197
|
+
expect(reopened.snapshot.sheets[1]!.cells).toContainEqual({ row: 9, column: 6, input: { kind: "value", value: 1400 } });
|
|
198
|
+
} finally { await workbook.close(); }
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("preserves the exact original when the table contains an unknown extension", async () => {
|
|
202
|
+
const parts = unzipSync(await fixture());
|
|
203
|
+
const definition = Object.keys(parts).find(path => /^xl\/pivotTables\/pivotTable\d+\.xml$/u.test(path))!;
|
|
204
|
+
parts[definition] = strToU8(strFromU8(parts[definition]!).replace("</pivotTableDefinition>", '<extLst><ext uri="special"/></extLst></pivotTableDefinition>'));
|
|
205
|
+
const bytes = zipSync(parts);
|
|
206
|
+
const file = openXlsx("回款", bytes);
|
|
207
|
+
expect(file.restrictions).toContain("未支持的数据透视表、缓存或工作表关系");
|
|
208
|
+
expect(file.snapshot.pivotTables).toBeUndefined();
|
|
209
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it("keeps a named group collapsed before a synthetic Values field in native XLSX", async () => {
|
|
214
|
+
const workbook = await openWorkbook(seed);
|
|
215
|
+
const target = parseWorkbookRange("report", "B3");
|
|
216
|
+
try {
|
|
217
|
+
await edit(workbook, { name: "setPivotTable", target, params: {
|
|
218
|
+
name: "分组汇总", source: { sheetId: "orders", range: "A1:D6" }, rowFields: [0], columnFields: [],
|
|
219
|
+
values: [{ field: 2, aggregate: "sum" }, { field: 2, aggregate: "countNumbers" }], filters: [],
|
|
220
|
+
valuesAxis: { axis: "row", position: 1 },
|
|
221
|
+
memberGroups: [{ field: 0, groups: [{ name: "区组合", members: ["华东", "华南"] }] }]
|
|
222
|
+
} });
|
|
223
|
+
const id = workbook.pivotTables()[0]!.id;
|
|
224
|
+
await edit(workbook, { name: "setPivotItemExpanded", target, params: { id, field: 0, level: "members", item: "区组合", expanded: false } });
|
|
225
|
+
const table = workbook.pivotTables()[0]!;
|
|
226
|
+
expect(table.output).toEqual(parseWorkbookRange("report", "B3:E7"));
|
|
227
|
+
const written = createXlsx(workbook.snapshot());
|
|
228
|
+
const saved = openXlsx("保存的分组", written);
|
|
229
|
+
expect(saved.restrictions).toEqual([]);
|
|
230
|
+
expect(saved.snapshot.pivotTables?.[0]).toMatchObject({
|
|
231
|
+
collapsedItems: [{ field: 0, level: "members", items: ["区组合"] }],
|
|
232
|
+
valuesAxis: { axis: "row", position: 1 }
|
|
233
|
+
});
|
|
234
|
+
const reopened = await openWorkbook(saved.snapshot, { appearance: saved.appearance });
|
|
235
|
+
try {
|
|
236
|
+
const { output: { sheetId }, id: pivotId } = reopened.pivotTables()[0]!;
|
|
237
|
+
expect(reopened.readCell({ sheetId, row: 3, column: 4 }).result).toMatchObject({ value: 1470 });
|
|
238
|
+
expect(reopened.readCell({ sheetId, row: 4, column: 4 }).result).toMatchObject({ value: 5 });
|
|
239
|
+
await edit(reopened, { name: "setPivotItemExpanded", target: parseWorkbookRange(sheetId, "B3"),
|
|
240
|
+
params: { id: pivotId, field: 0, level: "members", expanded: true } });
|
|
241
|
+
expect(reopened.pivotTables()[0]?.collapsedItems).toBeUndefined();
|
|
242
|
+
} finally { await reopened.close(); }
|
|
243
|
+
} finally { await workbook.close(); }
|
|
244
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { planWorkbookPivot, sameWorkbookPivot, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
3
|
+
import { editPartRelationships, relationshipsPath } from "../../opc/relationships";
|
|
4
|
+
import { child, children, contentTypeNs, parsePart, relationshipNs, rootOf, spreadNs, writePart } from "../../opc/xml";
|
|
5
|
+
import type { XlsxPackage } from "../../package/types";
|
|
6
|
+
import { writeXlsxPivotCache } from "../cache/write";
|
|
7
|
+
import { writeXlsxPivotDefinition } from "../definition/write";
|
|
8
|
+
import { pivotContentTypes, pivotRoles } from "../xml";
|
|
9
|
+
|
|
10
|
+
/** @param before - Used baseline. @param after - Current workbook. @returns Whether native definition or cache data changed. */
|
|
11
|
+
export function sameXlsxPivots(before: WorkbookSnapshot | undefined, after: WorkbookSnapshot): boolean {
|
|
12
|
+
const prior = before?.pivotTables ?? [], next = after.pivotTables ?? [];
|
|
13
|
+
return prior.length === next.length && prior.every((table, index) => sameWorkbookPivot(table, next[index]!));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** @param source - Original workbook and any owned pivot parts. @param parts - Mutable staging package.
|
|
17
|
+
* @param workbook - Native workbook element. @param snapshot - Current definitions and source names.
|
|
18
|
+
* @param sheetPaths - Native worksheet parts by stable identity. */
|
|
19
|
+
export function writeWorkbookPivots(source: XlsxPackage, parts: Record<string, Uint8Array>, workbook: Element,
|
|
20
|
+
snapshot: WorkbookSnapshot, sheetPaths: ReadonlyMap<string, string>): void {
|
|
21
|
+
const tables = snapshot.pivotTables ?? [];
|
|
22
|
+
const currentNames = new Map(snapshot.sheets.map(sheet => [sheet.id, sheet.name]));
|
|
23
|
+
const renamed = source.baseline?.sheets.some(sheet => sheet.name !== currentNames.get(sheet.id)
|
|
24
|
+
&& tables.some(table => table.source.sheetId === sheet.id));
|
|
25
|
+
if (!renamed && sameXlsxPivots(source.baseline, snapshot)) return;
|
|
26
|
+
const document = workbook.ownerDocument!;
|
|
27
|
+
const typesPath = "[Content_Types].xml";
|
|
28
|
+
const typesXml = parsePart(parts[typesPath], typesPath);
|
|
29
|
+
const types = rootOf(typesXml, contentTypeNs, "Types");
|
|
30
|
+
const native = editPartRelationships(parts, source.workbookPath);
|
|
31
|
+
const old = source.pivotGraph;
|
|
32
|
+
const previousDirectory = child(workbook, "pivotCaches");
|
|
33
|
+
if (previousDirectory) workbook.removeChild(previousDirectory);
|
|
34
|
+
|
|
35
|
+
// Remove only the graph validated at import. Drawings, hyperlinks, and worksheet
|
|
36
|
+
// registrations have already updated their own relationships on the same staging package.
|
|
37
|
+
if (old) {
|
|
38
|
+
for (const id of old.workbookRelations) native.remove(id);
|
|
39
|
+
for (const [path, ids] of old.worksheetRelations) {
|
|
40
|
+
if (!parts[relationshipsPath(path)]) continue;
|
|
41
|
+
const relationships = editPartRelationships(parts, path);
|
|
42
|
+
for (const id of ids) relationships.remove(id);
|
|
43
|
+
relationships.write();
|
|
44
|
+
}
|
|
45
|
+
for (const path of old.parts) delete parts[path];
|
|
46
|
+
for (const node of children(types, "Override")) {
|
|
47
|
+
if (old.parts.has((node.getAttribute("PartName") ?? "").slice(1))) types.removeChild(node);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const reserved = new Set(Object.keys(parts).map(path => path.toLowerCase()));
|
|
51
|
+
const directory = document.createElementNS(spreadNs, "pivotCaches");
|
|
52
|
+
const folder = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
|
|
53
|
+
let serial = 1, nextCacheId = 1;
|
|
54
|
+
/** @param stem - Directory and base name. @param type - Declared OPC type.
|
|
55
|
+
* @returns Free native path isolated from all existing parts. */
|
|
56
|
+
function allocate(stem: string, type: string): string {
|
|
57
|
+
let path: string;
|
|
58
|
+
do { path = folder + stem + serial++ + ".xml"; } while (reserved.has(path.toLowerCase()) || reserved.has(relationshipsPath(path).toLowerCase()));
|
|
59
|
+
reserved.add(path.toLowerCase());
|
|
60
|
+
const node = typesXml.createElementNS(contentTypeNs, "Override");
|
|
61
|
+
node.setAttribute("PartName", "/" + path);
|
|
62
|
+
node.setAttribute("ContentType", type);
|
|
63
|
+
types.appendChild(node);
|
|
64
|
+
return path;
|
|
65
|
+
}
|
|
66
|
+
const caches = new Map<string, { path: string; id: number; indexes: ReturnType<typeof writeXlsxPivotCache> }>();
|
|
67
|
+
for (const table of tables) {
|
|
68
|
+
const sheetName = currentNames.get(table.source.sheetId);
|
|
69
|
+
const sheetPath = sheetPaths.get(table.output.sheetId);
|
|
70
|
+
if (!sheetName || !sheetPath) throw new Error("数据透视表缺少来源或输出工作表。");
|
|
71
|
+
const { sheetId, startRow, startColumn } = table.output;
|
|
72
|
+
const plan = planWorkbookPivot(table.cache, table, { sheetId, row: startRow, column: startColumn });
|
|
73
|
+
// The native cache contains calculated definitions as well as shared items. Reports
|
|
74
|
+
// with different formulas or expanded fields need independent caches.
|
|
75
|
+
const key = JSON.stringify([table.source, table.cache, plan.dateFields, plan.numberFields, plan.memberFields, plan.layout.calculatedFields]);
|
|
76
|
+
let cache = caches.get(key);
|
|
77
|
+
if (!cache) {
|
|
78
|
+
const path = allocate("pivotCache/pivotCacheDefinition", pivotContentTypes.cache);
|
|
79
|
+
const records = allocate("pivotCache/pivotCacheRecords", pivotContentTypes.records);
|
|
80
|
+
const id = nextCacheId++;
|
|
81
|
+
cache = { path, id, indexes: writeXlsxPivotCache(parts, path, records, table, sheetName, plan, snapshot.dateSystem ?? "1900") };
|
|
82
|
+
caches.set(key, cache);
|
|
83
|
+
const entry = document.createElementNS(spreadNs, "pivotCache");
|
|
84
|
+
entry.setAttribute("cacheId", String(id));
|
|
85
|
+
entry.setAttributeNS(relationshipNs, "r:id", native.add(pivotRoles.cache, "/" + path));
|
|
86
|
+
directory.appendChild(entry);
|
|
87
|
+
}
|
|
88
|
+
const path = allocate("pivotTables/pivotTable", pivotContentTypes.definition);
|
|
89
|
+
const definition = editPartRelationships(parts, path);
|
|
90
|
+
definition.add(pivotRoles.cache, "/" + cache.path);
|
|
91
|
+
definition.write();
|
|
92
|
+
const sheet = editPartRelationships(parts, sheetPath);
|
|
93
|
+
sheet.add(pivotRoles.definition, "/" + path);
|
|
94
|
+
sheet.write();
|
|
95
|
+
parts[path] = writeXlsxPivotDefinition(path, table, cache.id, cache.indexes, plan);
|
|
96
|
+
}
|
|
97
|
+
if (tables.length) {
|
|
98
|
+
const after = children(workbook).find(node => ["smartTagPr", "smartTagTypes", "webPublishing", "fileRecoveryPr", "webPublishObjects", "extLst"].includes(node.localName ?? ""));
|
|
99
|
+
workbook.insertBefore(directory, after ?? null);
|
|
100
|
+
}
|
|
101
|
+
native.write();
|
|
102
|
+
parts[typesPath] = writePart(typesXml);
|
|
103
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { WorkbookPivotCache, WorkbookPivotCalculatedField, WorkbookPivotResolvedDateField, WorkbookPivotResolvedMemberField, WorkbookPivotResolvedNumberField,
|
|
2
|
+
WorkbookPivotValue, WorkbookRange } from "@quirekit/workbook";
|
|
3
|
+
|
|
4
|
+
/** Date grouping in the producer's native field index space. */
|
|
5
|
+
export interface XlsxPivotDateField extends WorkbookPivotResolvedDateField {
|
|
6
|
+
/** Explicit next coarser level, if the producer stored it. */
|
|
7
|
+
readonly parent?: number | undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Parsed typed pivot cache and its field-item namespaces. */
|
|
11
|
+
export interface XlsxPivotCache {
|
|
12
|
+
/** Worksheet source referenced by the cache definition. */
|
|
13
|
+
readonly source: WorkbookRange;
|
|
14
|
+
/** Values and headers in canonical source order. */
|
|
15
|
+
readonly cache: WorkbookPivotCache;
|
|
16
|
+
/** Calculated definitions keyed by their non-database native field. */
|
|
17
|
+
readonly calculatedFields: ReadonlyMap<number, WorkbookPivotCalculatedField>;
|
|
18
|
+
/** Native field-item lists, including generated date and member groups. */
|
|
19
|
+
readonly shared: readonly (readonly WorkbookPivotValue[])[];
|
|
20
|
+
/** Typed grouping definitions indexed by their original native field. */
|
|
21
|
+
readonly dateFields: ReadonlyMap<number, XlsxPivotDateField>;
|
|
22
|
+
/** Numeric ranges whose ordinals apply only when present on a grouping axis. */
|
|
23
|
+
readonly numberFields: ReadonlyMap<number, WorkbookPivotResolvedNumberField>;
|
|
24
|
+
/** Discrete groups indexed by the generated native field. */
|
|
25
|
+
readonly memberFields: ReadonlyMap<number, WorkbookPivotResolvedMemberField>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Exclusively owned pivot graph in one editable package. */
|
|
29
|
+
export interface XlsxPivotGraph {
|
|
30
|
+
/** Pivot cache relationship IDs owned by the workbook part. */
|
|
31
|
+
readonly workbookRelations: ReadonlySet<string>;
|
|
32
|
+
/** Worksheet part paths and their implicit pivot relationship IDs. */
|
|
33
|
+
readonly worksheetRelations: ReadonlyMap<string, ReadonlySet<string>>;
|
|
34
|
+
/** Native definitions, records, and their own relationship parts. */
|
|
35
|
+
readonly parts: ReadonlySet<string>;
|
|
36
|
+
}
|
package/src/pivot/xml.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Document, Element } from "@xmldom/xmldom";
|
|
2
|
+
import { strToU8 } from "fflate";
|
|
3
|
+
import { children, parsePart, relationshipNs, spreadNs } from "../opc/xml";
|
|
4
|
+
|
|
5
|
+
/** Relationship roles for the three parts of a worksheet PivotTable. */
|
|
6
|
+
export const pivotRoles = {
|
|
7
|
+
definition: relationshipNs + "/pivotTable",
|
|
8
|
+
cache: relationshipNs + "/pivotCacheDefinition",
|
|
9
|
+
records: relationshipNs + "/pivotCacheRecords"
|
|
10
|
+
} as const;
|
|
11
|
+
|
|
12
|
+
/** Native content-type members indexed by what the part stores. */
|
|
13
|
+
export const pivotContentTypes = {
|
|
14
|
+
definition: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",
|
|
15
|
+
cache: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml",
|
|
16
|
+
records: "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml"
|
|
17
|
+
} as const;
|
|
18
|
+
|
|
19
|
+
/** @param tag - Internal native root element. @param path - Designated part. @returns Standard SpreadsheetML document. */
|
|
20
|
+
export function pivotXml(tag: string, path: string): Document {
|
|
21
|
+
return parsePart(strToU8('<' + tag + ' xmlns="' + spreadNs + '" xmlns:r="' + relationshipNs + '"/>'), path);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @param node - Native pivot element. @param fields - Unqualified, validated XML attributes. */
|
|
25
|
+
export function pivotAttributes(node: Element, fields: Readonly<Record<string, string | number | boolean | undefined>>): void {
|
|
26
|
+
for (const [key, value] of Object.entries(fields)) if (value !== undefined) {
|
|
27
|
+
node.setAttribute(key, typeof value === "boolean" ? value ? "1" : "0" : String(value));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @param parent - Native container. @param name - Child element. @param fields - Native values.
|
|
32
|
+
* @returns New child. */
|
|
33
|
+
export function pivotChild(parent: Element, name: string, fields: Readonly<Record<string, string | number | boolean | undefined>> = {}): Element {
|
|
34
|
+
const child = parent.ownerDocument!.createElementNS(spreadNs, name);
|
|
35
|
+
pivotAttributes(child, fields);
|
|
36
|
+
parent.appendChild(child);
|
|
37
|
+
return child;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** @param parent - Optional native list. @param name - Only admitted entry name.
|
|
41
|
+
* @returns Same-namespace members, with any stated count checked against the contents. */
|
|
42
|
+
export function pivotMembers(parent: Element | undefined, name: string): Element[] {
|
|
43
|
+
if (!parent) return [];
|
|
44
|
+
const entries = children(parent);
|
|
45
|
+
if (entries.some(entry => entry.namespaceURI !== spreadNs || entry.localName !== name)
|
|
46
|
+
|| parent.hasAttribute("count") && parent.getAttribute("count") !== String(entries.length)) {
|
|
47
|
+
throw new Error("数据透视表部件的列表与计数不一致。");
|
|
48
|
+
}
|
|
49
|
+
return entries;
|
|
50
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { createXlsx, openXlsx } from "./index";
|
|
4
|
+
import { packageRelationshipNs, relationshipNs, spreadNs } from "./opc/xml";
|
|
5
|
+
|
|
6
|
+
const drawingNs = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing";
|
|
7
|
+
const drawingMainNs = "http://schemas.openxmlformats.org/drawingml/2006/main";
|
|
8
|
+
const chartNs = "http://schemas.openxmlformats.org/drawingml/2006/chart";
|
|
9
|
+
const sheetPath = "xl/worksheets/sheet1.xml";
|
|
10
|
+
const workbookRels = "xl/_rels/workbook.xml.rels";
|
|
11
|
+
|
|
12
|
+
/** @param id - Source relationship ID. @param type - Relationship kind. @param target - Relative part path.
|
|
13
|
+
* @returns Test relationship in a conventional OPC document. */
|
|
14
|
+
function relationship(id: string, type: string, target: string): string {
|
|
15
|
+
return `<Relationship Id="${id}" Type="${relationshipNs}/${type}" Target="${target}"/>`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param relationships - Serialized relationship children. @returns Complete OPC relationship part. */
|
|
19
|
+
function rels(relationships: string): Uint8Array {
|
|
20
|
+
return strToU8(`<Relationships xmlns="${packageRelationshipNs}">${relationships}</Relationships>`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @param dateSystem - Native workbook calendar for the fixture. @returns Minimal workbook package with a direct editing checkpoint. */
|
|
24
|
+
function workbookParts(dateSystem: "1900" | "1904" = "1900"): Record<string, Uint8Array> {
|
|
25
|
+
return unzipSync(createXlsx({
|
|
26
|
+
version: 1, revision: 0, id: "book", name: "报表", dateSystem,
|
|
27
|
+
sheets: [{ id: "report", name: "报表", cells: [] }]
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @param dateSystem - Native workbook calendar. @returns A package with a source date display style. */
|
|
32
|
+
function dateWorkbookParts(dateSystem: "1900" | "1904"): Record<string, Uint8Array> {
|
|
33
|
+
const parts = workbookParts(dateSystem);
|
|
34
|
+
parts[workbookRels] = strToU8(strFromU8(parts[workbookRels]!).replace("</Relationships>",
|
|
35
|
+
relationship("dateStyles", "styles", "styles.xml") + "</Relationships>"));
|
|
36
|
+
parts["xl/styles.xml"] = strToU8(`<styleSheet xmlns="${spreadNs}">
|
|
37
|
+
<numFmts count="1"><numFmt numFmtId="164" formatCode="mm/dd/yy"/></numFmts>
|
|
38
|
+
<cellXfs count="2"><xf numFmtId="0"/><xf numFmtId="164"/></cellXfs>
|
|
39
|
+
</styleSheet>`);
|
|
40
|
+
return parts;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
describe("XLSX imported presentation", () => {
|
|
44
|
+
it.each([["1900", 46328], ["1904", 44866]] as const)("projects ISO dates using the %s epoch and keeps the original XML", (system, serial) => {
|
|
45
|
+
const parts = dateWorkbookParts(system);
|
|
46
|
+
parts[sheetPath] = strToU8(`<worksheet xmlns="${spreadNs}"><sheetData><row r="1">
|
|
47
|
+
<c r="A1" s="1" t="d"><v>2026-11-02T00:00:00.000Z</v></c>
|
|
48
|
+
<c r="B1" t="d"><v>2026-11-02T12:00:00.250</v></c>
|
|
49
|
+
<c r="C1" t="d"><v>2026-11-02</v></c>
|
|
50
|
+
<c r="D1" t="d"><v>2026-02-30</v></c>
|
|
51
|
+
<c r="E1" t="d"><v>2026-11-02T00:00:00+08:00</v></c>
|
|
52
|
+
<c r="F1" t="str"><v>2026-11-02</v></c>
|
|
53
|
+
</row></sheetData></worksheet>`);
|
|
54
|
+
const bytes = zipSync(parts);
|
|
55
|
+
const file = openXlsx("Dates", bytes);
|
|
56
|
+
const sheet = file.snapshot.sheets[0]!;
|
|
57
|
+
expect(file.snapshot.dateSystem).toBe(system);
|
|
58
|
+
expect(sheet.cells.map(({ input }) => input)).toEqual([
|
|
59
|
+
{ kind: "value", value: serial }, { kind: "value", value: serial + 0.5 + 0.25 / 86_400 },
|
|
60
|
+
{ kind: "value", value: serial }, { kind: "value", value: "2026-02-30" },
|
|
61
|
+
{ kind: "value", value: "2026-11-02T00:00:00+08:00" }, { kind: "value", value: "2026-11-02" }
|
|
62
|
+
]);
|
|
63
|
+
const styleId = file.appearance.sheets.get(sheet.id)?.cellStyles[0]?.[0];
|
|
64
|
+
expect(file.appearance.styles[styleId!]?.numberFormat).toBe("mm/dd/yy");
|
|
65
|
+
expect(file.restrictions).toContain("原生日期或错误常量");
|
|
66
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it.each([["1900", 46328], ["1904", 44866]] as const)("edits ISO dates and retains manual date caches in the %s calendar", (system, serial) => {
|
|
70
|
+
const parts = dateWorkbookParts(system);
|
|
71
|
+
const workbookPath = "xl/workbook.xml";
|
|
72
|
+
parts[workbookPath] = strToU8(strFromU8(parts[workbookPath]!).replace('<calcPr fullCalcOnLoad="1"',
|
|
73
|
+
'<calcPr calcMode="manual" calcCompleted="1" fullCalcOnLoad="0"'));
|
|
74
|
+
parts[sheetPath] = strToU8(`<worksheet xmlns="${spreadNs}"><sheetData><row r="1">
|
|
75
|
+
<c r="A1" s="1" t="d"><v>2026-11-02</v></c>
|
|
76
|
+
<c r="B1" s="1" t="d"><f>C1+1</f><v>2026-11-03T12:00:00.250</v></c>
|
|
77
|
+
<c r="C1" s="1" t="d"><v>2026-11-02T12:00:00.250Z</v></c>
|
|
78
|
+
</row></sheetData></worksheet>`);
|
|
79
|
+
const bytes = zipSync(parts);
|
|
80
|
+
const file = openXlsx("Native dates", bytes);
|
|
81
|
+
const { snapshot } = file;
|
|
82
|
+
const sheet = snapshot.sheets[0]!;
|
|
83
|
+
const expectedCache = { status: "value", value: serial + 1 + 43_200.25 / 86_400 };
|
|
84
|
+
expect(file.restrictions).toEqual([]);
|
|
85
|
+
expect(snapshot.formulaPendingRevision).toBeUndefined();
|
|
86
|
+
expect(snapshot.formulaResults).toEqual([{ sheetId: sheet.id, row: 0, column: 1, result: expectedCache }]);
|
|
87
|
+
expect(file.write(snapshot)).toEqual(bytes);
|
|
88
|
+
|
|
89
|
+
const changed = { ...sheet.cells[0]!, input: { kind: "value" as const, value: serial + 7 } };
|
|
90
|
+
const output = file.write({ ...snapshot, revision: 1, sheets: [{ ...sheet, cells: [changed, ...sheet.cells.slice(1)] }] });
|
|
91
|
+
const savedParts = unzipSync(output);
|
|
92
|
+
const xml = strFromU8(savedParts[sheetPath]!);
|
|
93
|
+
expect(xml).toContain(`<c r="A1" s="1"><v>${serial + 7}</v></c>`);
|
|
94
|
+
expect(xml).toContain(`<c r="C1" s="1" t="d"><v>2026-11-02T12:00:00.250Z</v></c>`);
|
|
95
|
+
expect(savedParts["xl/styles.xml"]).toEqual(parts["xl/styles.xml"]);
|
|
96
|
+
|
|
97
|
+
const reopened = openXlsx("Native dates", output);
|
|
98
|
+
expect(reopened.restrictions).toEqual([]);
|
|
99
|
+
expect(reopened.snapshot.dateSystem).toBe(system);
|
|
100
|
+
expect(reopened.snapshot.formulaResults?.[0]?.result).toEqual(expectedCache);
|
|
101
|
+
expect(reopened.snapshot.sheets[0]?.cells[0]).toEqual(changed);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("retains shared styles, styled blanks and source geometry independently of workbook data", () => {
|
|
105
|
+
const parts = workbookParts();
|
|
106
|
+
parts[workbookRels] = strToU8(strFromU8(parts[workbookRels]!).replace("</Relationships>",
|
|
107
|
+
relationship("customStyles", "styles", "formats/native.xml") + relationship("customTheme", "theme", "theme/custom.xml") + "</Relationships>"));
|
|
108
|
+
parts["xl/formats/native.xml"] = strToU8(`<styleSheet xmlns="${spreadNs}">
|
|
109
|
+
<fonts><font><sz val="11"/><name val="Calibri"/></font><font><sz val="16"/><name val="Arial"/><b/><color theme="1" tint="0.4"/></font></fonts>
|
|
110
|
+
<fills><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="solid"><fgColor theme="4"/></patternFill></fill></fills>
|
|
111
|
+
<borders><border/><border><bottom style="thin"><color indexed="17"/></bottom></border></borders>
|
|
112
|
+
<cellStyleXfs><xf fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
|
|
113
|
+
<cellXfs><xf xfId="0"/><xf xfId="0" fontId="1" fillId="1" borderId="1"><alignment horizontal="center" vertical="center"/></xf></cellXfs>
|
|
114
|
+
<cellStyles><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>
|
|
115
|
+
</styleSheet>`);
|
|
116
|
+
parts["xl/theme/custom.xml"] = strToU8(`<a:theme xmlns:a="${drawingMainNs}"><a:themeElements><a:clrScheme>
|
|
117
|
+
<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>
|
|
118
|
+
<a:accent1><a:srgbClr val="336699"/></a:accent1>
|
|
119
|
+
</a:clrScheme></a:themeElements></a:theme>`);
|
|
120
|
+
parts[sheetPath] = strToU8(`<worksheet xmlns="${spreadNs}">
|
|
121
|
+
<sheetViews><sheetView workbookViewId="0" showGridLines="0"/></sheetViews>
|
|
122
|
+
<sheetFormatPr defaultColWidth="12.5" defaultRowHeight="30"/>
|
|
123
|
+
<cols><col min="2" max="4" width="18"/><col min="5" max="5" width="10" hidden="1"/></cols>
|
|
124
|
+
<sheetData><row r="1" ht="36"><c r="A1" s="1" t="inlineStr"><is><t>月度合计</t></is></c><c r="B1" s="1"/></row></sheetData>
|
|
125
|
+
<mergeCells><mergeCell ref="A1:B1"/></mergeCells>
|
|
126
|
+
</worksheet>`);
|
|
127
|
+
const bytes = zipSync(parts);
|
|
128
|
+
const file = openXlsx("报表", bytes);
|
|
129
|
+
const sheet = file.snapshot.sheets[0]!;
|
|
130
|
+
expect(sheet.cells).toEqual([{ row: 0, column: 0, input: { kind: "value", value: "月度合计" } }]);
|
|
131
|
+
expect(file.appearance.normal).toMatchObject({ fontFamily: "Calibri", fontSize: 11 });
|
|
132
|
+
expect(file.appearance.styles[1]).toMatchObject({
|
|
133
|
+
fontFamily: "Arial", fontSize: 16, bold: true, color: "#666666", background: "#336699",
|
|
134
|
+
horizontal: "center", vertical: "center", borders: { bottom: { stroke: "thin", color: "#008000" } }
|
|
135
|
+
});
|
|
136
|
+
const view = file.appearance.sheets.get(sheet.id)!;
|
|
137
|
+
expect(view).toMatchObject({
|
|
138
|
+
defaultColumnWidth: 12.5, defaultRowHeight: 40, showGridlines: false,
|
|
139
|
+
cellStyles: { 0: { 0: 1, 1: 1 } }, columns: [{ first: 1, last: 3, size: 18 }, { first: 4, last: 4, hidden: true }],
|
|
140
|
+
merges: [{ sheetId: sheet.id, startRow: 0, startColumn: 0, endRow: 0, endColumn: 1 }]
|
|
141
|
+
});
|
|
142
|
+
expect(view.rows.get(0)?.size).toBe(48);
|
|
143
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("resolves anchored local chart parts and retains sparse cached points and labels", () => {
|
|
147
|
+
const parts = workbookParts();
|
|
148
|
+
parts[sheetPath] = strToU8(`<worksheet xmlns="${spreadNs}" xmlns:r="${relationshipNs}"><sheetData/><drawing r:id="draw"/></worksheet>`);
|
|
149
|
+
parts["xl/worksheets/_rels/sheet1.xml.rels"] = rels(relationship("draw", "drawing", "../drawings/report.xml"));
|
|
150
|
+
parts["xl/drawings/_rels/report.xml.rels"] = rels(relationship("ring", "chart", "../charts/report.xml"));
|
|
151
|
+
parts["xl/drawings/report.xml"] = strToU8(`<xdr:wsDr xmlns:xdr="${drawingNs}" xmlns:a="${drawingMainNs}" xmlns:c="${chartNs}" xmlns:r="${relationshipNs}">
|
|
152
|
+
<xdr:twoCellAnchor>
|
|
153
|
+
<xdr:from><xdr:col>1</xdr:col><xdr:colOff>9525</xdr:colOff><xdr:row>2</xdr:row><xdr:rowOff>19050</xdr:rowOff></xdr:from>
|
|
154
|
+
<xdr:to><xdr:col>4</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>8</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to>
|
|
155
|
+
<xdr:graphicFrame><a:graphic><a:graphicData uri="${chartNs}"><c:chart r:id="ring"/></a:graphicData></a:graphic></xdr:graphicFrame>
|
|
156
|
+
</xdr:twoCellAnchor>
|
|
157
|
+
</xdr:wsDr>`);
|
|
158
|
+
parts["xl/charts/report.xml"] = strToU8(`<c:chartSpace xmlns:c="${chartNs}"><c:chart><c:plotArea><c:doughnutChart>
|
|
159
|
+
<c:ser>
|
|
160
|
+
<c:tx><c:v>年度合计</c:v></c:tx>
|
|
161
|
+
<c:cat><c:strRef><c:f>'报表'!$A$1:$A$3</c:f><c:strCache><c:ptCount val="3"/>
|
|
162
|
+
<c:pt idx="2"><c:v>交通</c:v></c:pt><c:pt idx="0"><c:v>餐饮</c:v></c:pt></c:strCache></c:strRef></c:cat>
|
|
163
|
+
<c:val><c:numRef><c:f>报表!B1:B3</c:f><c:numCache><c:ptCount val="3"/>
|
|
164
|
+
<c:pt idx="2"><c:v>0</c:v></c:pt><c:pt idx="0"><c:v>7</c:v></c:pt></c:numCache></c:numRef></c:val>
|
|
165
|
+
</c:ser>
|
|
166
|
+
<c:dLbls><c:showVal val="1"/><c:showCatName val="1"/></c:dLbls>
|
|
167
|
+
<c:holeSize val="50"/>
|
|
168
|
+
</c:doughnutChart></c:plotArea></c:chart></c:chartSpace>`);
|
|
169
|
+
const bytes = zipSync(parts);
|
|
170
|
+
const file = openXlsx("报表", bytes);
|
|
171
|
+
expect(file.charts).toMatchObject([{
|
|
172
|
+
anchor: { sheetId: file.snapshot.sheets[0]!.id, from: { row: 2, column: 1, x: 1, y: 2 }, to: { row: 8, column: 4, x: 0, y: 0 } },
|
|
173
|
+
sources: [
|
|
174
|
+
{ role: "categories", range: { sheetId: file.snapshot.sheets[0]!.id, startRow: 0, startColumn: 0, endRow: 2, endColumn: 0 } },
|
|
175
|
+
{ role: "values", range: { sheetId: file.snapshot.sheets[0]!.id, startRow: 0, startColumn: 1, endRow: 2, endColumn: 1 } }
|
|
176
|
+
],
|
|
177
|
+
preview: {
|
|
178
|
+
presentation: { dataLabels: true, legend: "none" },
|
|
179
|
+
plot: { kind: "doughnut", categoryLabels: true, holeRatio: 0.5,
|
|
180
|
+
series: [{ name: "年度合计", categories: ["餐饮", "", "交通"], values: [7, null, 0] }] }
|
|
181
|
+
}
|
|
182
|
+
}]);
|
|
183
|
+
expect(file.restrictions).toContain("绘图或图表");
|
|
184
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
185
|
+
});
|
|
186
|
+
});
|