@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,95 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { WorkbookAppearance, WorkbookCellAppearance, WorkbookCellBorder } from "@quirekit/workbook";
|
|
3
|
+
import { child, children, isTrue, readIndex, readSize } from "../opc/xml";
|
|
4
|
+
import { styleColorReader } from "./color";
|
|
5
|
+
import { builtinNumberFormats } from "./numbers";
|
|
6
|
+
import { appliedStyleIndex } from "./reference";
|
|
7
|
+
|
|
8
|
+
const horizontal = { left: "left", center: "center", centerContinuous: "center", right: "right", justify: "justify", distributed: "distributed" } as const;
|
|
9
|
+
const vertical = { top: "top", center: "center", bottom: "bottom" } as const;
|
|
10
|
+
const strokes = new Set<WorkbookCellBorder["stroke"]>([
|
|
11
|
+
"hair", "thin", "medium", "thick", "dotted", "dashed", "dashDot", "dashDotDot",
|
|
12
|
+
"mediumDashed", "mediumDashDot", "mediumDashDotDot", "slantDashDot", "double"
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
/** @param edge - SpreadsheetML edge. @returns Modeled stroke, if present. */
|
|
16
|
+
export function readWorkbookBorderStroke(edge: Element | undefined): WorkbookCellBorder["stroke"] | undefined {
|
|
17
|
+
const stroke = edge?.getAttribute("style") as WorkbookCellBorder["stroke"];
|
|
18
|
+
return strokes.has(stroke) ? stroke : undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param nodes - Style collection. @param node - Concrete style. @param base - Named base style.
|
|
22
|
+
* @param key - Index shared by the two styles. @param apply - Flag overriding named style.
|
|
23
|
+
* @returns Selected table entry, respecting an explicit opt-out. */
|
|
24
|
+
function stylePart(nodes: readonly Element[], node: Element, base: Element | undefined, key: string, apply: string): Element | undefined {
|
|
25
|
+
const index = appliedStyleIndex(node, base, key, apply);
|
|
26
|
+
return index === undefined ? undefined : nodes[index];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param font - SpreadsheetML font. @param name - Property element. @returns True for an enabled property. */
|
|
30
|
+
function fontFlag(font: Element, name: string): boolean {
|
|
31
|
+
const node = child(font, name);
|
|
32
|
+
return node !== undefined && !["0", "false", "none"].includes(node.getAttribute("val") ?? "");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** @param node - Optional styleSheet. @param theme - Resolved workbook theme.
|
|
36
|
+
* @returns Normal style and styles in original index order. */
|
|
37
|
+
export function readWorkbookStyles(node: Element | undefined, theme: readonly string[]): Pick<WorkbookAppearance, "normal" | "styles" | "unresolvedFillStyles"> {
|
|
38
|
+
if (!node) return { styles: [] };
|
|
39
|
+
const color = styleColorReader(child(node, "colors"), theme);
|
|
40
|
+
/** @param name - Style collection. @returns Its ordered entries. */
|
|
41
|
+
const table = (name: string) => {
|
|
42
|
+
const collection = child(node, name);
|
|
43
|
+
return collection ? children(collection) : [];
|
|
44
|
+
};
|
|
45
|
+
const fonts = table("fonts"), fills = table("fills"), borders = table("borders"), bases = table("cellStyleXfs");
|
|
46
|
+
const formats = new Map(table("numFmts").map(format => [readIndex(format, "numFmtId"), format.getAttribute("formatCode")]));
|
|
47
|
+
const namedNormal = table("cellStyles").find(entry => entry.getAttribute("builtinId") === "0" || entry.getAttribute("name") === "Normal");
|
|
48
|
+
const unresolvedFillStyles = new Set<number>();
|
|
49
|
+
|
|
50
|
+
/** @param style - Source cell or named style. @param base - Its explicit named base.
|
|
51
|
+
* @param index - Effective cell style index for marking an unresolved fill. @returns Derived display tuple. */
|
|
52
|
+
function format(style: Element, base: Element | undefined, index?: number): WorkbookCellAppearance {
|
|
53
|
+
const font = stylePart(fonts, style, base, "fontId", "applyFont");
|
|
54
|
+
const fill = stylePart(fills, style, base, "fillId", "applyFill");
|
|
55
|
+
const border = stylePart(borders, style, base, "borderId", "applyBorder");
|
|
56
|
+
const pattern = fill && child(fill, "patternFill");
|
|
57
|
+
const patternType = pattern?.getAttribute("patternType");
|
|
58
|
+
const background = patternType === "solid" ? color(child(pattern!, "fgColor")) : undefined;
|
|
59
|
+
if (index !== undefined && fill && !background && (!pattern || patternType && patternType !== "none")) unresolvedFillStyles.add(index);
|
|
60
|
+
const alignFlag = style.getAttribute("applyAlignment");
|
|
61
|
+
const baseAlign = base && child(base, "alignment");
|
|
62
|
+
const align = !["0", "false"].includes(alignFlag ?? "") ? child(style, "alignment") ?? baseAlign : baseAlign;
|
|
63
|
+
const numberId = appliedStyleIndex(style, base, "numFmtId", "applyNumberFormat") ?? 0;
|
|
64
|
+
const formatCode = formats.get(numberId) || builtinNumberFormats.get(numberId);
|
|
65
|
+
const edges: Partial<Record<"top" | "right" | "bottom" | "left", WorkbookCellBorder>> = {};
|
|
66
|
+
if (border) for (const side of ["top", "right", "bottom", "left"] as const) {
|
|
67
|
+
const edge = child(border, side);
|
|
68
|
+
const stroke = readWorkbookBorderStroke(edge);
|
|
69
|
+
if (edge && stroke) edges[side] = { stroke, color: color(child(edge, "color")) ?? "#000000" };
|
|
70
|
+
}
|
|
71
|
+
const h = align?.getAttribute("horizontal"), v = align?.getAttribute("vertical");
|
|
72
|
+
const indent = readIndex(align, "indent");
|
|
73
|
+
return {
|
|
74
|
+
...(font && {
|
|
75
|
+
fontFamily: child(font, "name")?.getAttribute("val") || undefined,
|
|
76
|
+
fontSize: readSize(child(font, "sz"), "val"),
|
|
77
|
+
bold: fontFlag(font, "b"), italic: fontFlag(font, "i"), underline: fontFlag(font, "u"), strike: fontFlag(font, "strike"),
|
|
78
|
+
color: color(child(font, "color"))
|
|
79
|
+
}),
|
|
80
|
+
background,
|
|
81
|
+
horizontal: h && Object.hasOwn(horizontal, h) ? horizontal[h as keyof typeof horizontal] : undefined,
|
|
82
|
+
vertical: v && Object.hasOwn(vertical, v) ? vertical[v as keyof typeof vertical] : undefined,
|
|
83
|
+
...(indent !== undefined && indent <= 250 && { indent }),
|
|
84
|
+
wrap: align ? isTrue(align.getAttribute("wrapText")) : undefined,
|
|
85
|
+
shrinkToFit: align ? isTrue(align.getAttribute("shrinkToFit")) : undefined,
|
|
86
|
+
borders: Object.keys(edges).length ? edges : undefined,
|
|
87
|
+
numberFormat: formatCode || undefined
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const styles = table("cellXfs").map((style, index) => format(style, bases[readIndex(style, "xfId") ?? 0], index));
|
|
92
|
+
const normal = bases[readIndex(namedNormal, "xfId") ?? 0];
|
|
93
|
+
return { normal: normal ? format(normal, undefined, styles.length ? undefined : 0) : styles[0], styles,
|
|
94
|
+
...(unresolvedFillStyles.size && { unresolvedFillStyles }) };
|
|
95
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { readIndex } from "../opc/xml";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @param style - Concrete cell or named style.
|
|
6
|
+
* @param base - The named style it refers to.
|
|
7
|
+
* @param key - The id attribute shared by style records.
|
|
8
|
+
* @param apply - Flag for the style group.
|
|
9
|
+
* @returns Active index, accounting for explicit inheritance.
|
|
10
|
+
*/
|
|
11
|
+
export function appliedStyleIndex(style: Element, base: Element | undefined, key: string, apply: string): number | undefined {
|
|
12
|
+
const inherited = readIndex(base, key);
|
|
13
|
+
return ["0", "false"].includes(style.getAttribute(apply) ?? "") ? inherited : readIndex(style, key) ?? inherited;
|
|
14
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { WorkbookConditionalStyle } from "@quirekit/workbook";
|
|
2
|
+
|
|
3
|
+
/** SpreadsheetML differential style record with additional native number formatting. */
|
|
4
|
+
export interface XlsxDifferentialStyle extends WorkbookConditionalStyle {
|
|
5
|
+
/** Explicit absence of a fill in a color criterion. */
|
|
6
|
+
readonly noFill?: true | undefined;
|
|
7
|
+
/** Built-in percentage format used by a native progress column. */
|
|
8
|
+
readonly progressPercent?: true | undefined;
|
|
9
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { expect, it } from "vitest";
|
|
5
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
6
|
+
import { openWorkbook, parseWorkbookRange, type WorkbookCellFormat, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
7
|
+
import { createXlsx, openXlsx } from "../index";
|
|
8
|
+
|
|
9
|
+
const accent: WorkbookCellFormat = {
|
|
10
|
+
bold: true, fontFamily: "Aptos", fontSize: 16, color: "#1F4E78", background: "#CCEEFF",
|
|
11
|
+
horizontal: "center", vertical: "center", wrap: true, numberFormat: "0.00%",
|
|
12
|
+
borders: { bottom: { stroke: "thin", color: "#333333" } }
|
|
13
|
+
};
|
|
14
|
+
const seed: WorkbookSnapshot = {
|
|
15
|
+
version: 1, revision: 0, id: "report", name: "统计表",
|
|
16
|
+
sheets: [{ id: "report", name: "统计表", cells: [
|
|
17
|
+
{ row: 0, column: 0, input: { kind: "value", value: 0.36 } },
|
|
18
|
+
{ row: 0, column: 1, input: { kind: "formula", formula: "=A1*2" } }
|
|
19
|
+
], formats: [0, 1, 2].map(column => ({ row: 0, column, format: accent })) }]
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
it("writes canonical formats as shared native XLSX styles, including blank cells", () => {
|
|
23
|
+
const file = openXlsx("统计表", createXlsx(seed, { result: () => ({ status: "value", value: 0.72 }) }));
|
|
24
|
+
const { id } = file.snapshot.sheets[0]!;
|
|
25
|
+
const refs = file.appearance.sheets.get(id)!.cellStyles[0]!;
|
|
26
|
+
expect(refs[0]).toBe(refs[1]);
|
|
27
|
+
expect(refs[2]).toBe(refs[1]);
|
|
28
|
+
expect(file.appearance.styles[refs[2]!]).toMatchObject(accent);
|
|
29
|
+
expect(file.snapshot.sheets[0]?.cells).toHaveLength(2);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("isolates changed cells and preserves source attributes, cached formulas and adjacent cells", async () => {
|
|
33
|
+
const source = unzipSync(createXlsx(seed, { result: () => ({ status: "value", value: 0.72 }) }));
|
|
34
|
+
const original = strFromU8(source["xl/styles.xml"]!);
|
|
35
|
+
source["xl/styles.xml"] = strToU8(original.replace("<alignment ", '<alignment textRotation="15" '));
|
|
36
|
+
const file = openXlsx("统计表", zipSync(source));
|
|
37
|
+
const id = file.snapshot.sheets[0]!.id;
|
|
38
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
39
|
+
try {
|
|
40
|
+
expect(workbook.readFormat({ sheetId: id, row: 0, column: 0 })).toMatchObject({ numberFormat: "0.00%" });
|
|
41
|
+
const edit = workbook.prepare({ operationId: "style", baseRevision: 0, commands: [{
|
|
42
|
+
name: "setCellFormat", target: parseWorkbookRange(id, "A1"), params: {
|
|
43
|
+
bold: false, background: null, wrap: false, numberFormat: "yyyy-mm-dd",
|
|
44
|
+
borders: { left: { stroke: "dotted", color: "#097B60" } }
|
|
45
|
+
}
|
|
46
|
+
}] });
|
|
47
|
+
await workbook.commit(edit.id);
|
|
48
|
+
const bytes = file.write(workbook.snapshot());
|
|
49
|
+
const reopened = openXlsx("统计表", bytes);
|
|
50
|
+
const { cellStyles } = reopened.appearance.sheets.get(id)!;
|
|
51
|
+
const style = reopened.appearance.styles[cellStyles[0]![0]!]!;
|
|
52
|
+
expect(style).toMatchObject({
|
|
53
|
+
bold: false, fontFamily: "Aptos", wrap: false, horizontal: "center", numberFormat: "yyyy-mm-dd",
|
|
54
|
+
borders: { left: { stroke: "dotted", color: "#097B60" }, bottom: { stroke: "thin", color: "#333333" } }
|
|
55
|
+
});
|
|
56
|
+
expect(style.background).toBeUndefined();
|
|
57
|
+
expect(reopened.appearance.styles[cellStyles[0]![1]!]).toMatchObject(accent);
|
|
58
|
+
const parts = unzipSync(bytes);
|
|
59
|
+
expect(strFromU8(parts["xl/styles.xml"]!)).toMatch(/textRotation="15"[^>]*wrapText="0"/u);
|
|
60
|
+
expect(strFromU8(parts["xl/worksheets/sheet1.xml"]!)).toContain("<f>A1*2</f><v>0.72</v>");
|
|
61
|
+
} finally { await workbook.close(); }
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("preserves a native shrink-to-fit flag and writes explicit changes through the shared style transaction", async () => {
|
|
65
|
+
const bytes = Uint8Array.from(readFileSync(new URL("../../test/fixtures/text-fit.xlsx", import.meta.url)));
|
|
66
|
+
const file = openXlsx("文字适配", bytes);
|
|
67
|
+
const { id: sheetId } = file.snapshot.sheets[0]!;
|
|
68
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
69
|
+
const address = { sheetId, row: 0, column: 0 };
|
|
70
|
+
try {
|
|
71
|
+
expect(workbook.readFormat(address)).toMatchObject({ shrinkToFit: true, fontSize: 16, numberFormat: "0.00" });
|
|
72
|
+
expect(file.write(workbook.snapshot())).toEqual(bytes);
|
|
73
|
+
const candidate = workbook.prepare({ operationId: "clear-shrink", baseRevision: 0, commands: [{
|
|
74
|
+
name: "setCellFormat", target: parseWorkbookRange(sheetId, "A1"), params: { shrinkToFit: false }
|
|
75
|
+
}] });
|
|
76
|
+
await workbook.commit(candidate.id);
|
|
77
|
+
const output = file.write(workbook.snapshot());
|
|
78
|
+
const updated = openXlsx("文字适配", output);
|
|
79
|
+
const source = updated.appearance.sheets.get(sheetId)?.cellStyles[0]!;
|
|
80
|
+
expect(updated.appearance.styles[source[0]!]).toMatchObject({ shrinkToFit: false, fontSize: 16, horizontal: "center", numberFormat: "0.00" });
|
|
81
|
+
expect(updated.appearance.styles[source[1]!]).toMatchObject({ shrinkToFit: true, fontSize: 16 });
|
|
82
|
+
expect(strFromU8(unzipSync(output)["xl/styles.xml"]!)).toContain('shrinkToFit="0"');
|
|
83
|
+
expect(updated.snapshot.sheets[0]?.cells[0]?.input).toEqual({ kind: "value", value: 123456.78 });
|
|
84
|
+
await workbook.undo("restore-shrink");
|
|
85
|
+
expect(workbook.readFormat(address).shrinkToFit).toBe(true);
|
|
86
|
+
expect(file.write(workbook.snapshot())).toEqual(bytes);
|
|
87
|
+
} finally { await workbook.close(); }
|
|
88
|
+
});
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { XMLSerializer, type Element } from "@xmldom/xmldom";
|
|
2
|
+
import { strToU8 } from "fflate";
|
|
3
|
+
import { defaultWorkbookNormalFont, type WorkbookCellFormat } from "@quirekit/workbook";
|
|
4
|
+
import { child, children, parsePart, readIndex, rootOf, spreadNs } from "../opc/xml";
|
|
5
|
+
import { builtinNumberFormats } from "./numbers";
|
|
6
|
+
import { writeXlsxAlignment, writeXlsxBorder, writeXlsxFont, xlsxFill } from "./parts";
|
|
7
|
+
import { appliedStyleIndex } from "./reference";
|
|
8
|
+
import { writeXlsxDifferential } from "./differential";
|
|
9
|
+
import type { XlsxDifferentialStyle } from "./types";
|
|
10
|
+
import { writeXlsxComplement } from "./checkbox/style";
|
|
11
|
+
|
|
12
|
+
const collections = ["numFmts", "fonts", "fills", "borders", "cellStyleXfs", "cellXfs", "cellStyles", "dxfs", "tableStyles", "colors", "extLst"];
|
|
13
|
+
const initialStyles = `<styleSheet xmlns="${spreadNs}">
|
|
14
|
+
<fonts count="1"><font><sz val="${defaultWorkbookNormalFont.fontSize}"/><color theme="1"/><name val="${defaultWorkbookNormalFont.fontFamily}"/><family val="2"/><scheme val="minor"/></font></fonts>
|
|
15
|
+
<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>
|
|
16
|
+
<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
|
|
17
|
+
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
|
|
18
|
+
<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs>
|
|
19
|
+
<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>
|
|
20
|
+
</styleSheet>`;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param root - Style sheet element.
|
|
24
|
+
* @param name - Child collection.
|
|
25
|
+
* @returns Existing or correctly ordered collection.
|
|
26
|
+
*/
|
|
27
|
+
function ensureCollection(root: Element, name: string): Element {
|
|
28
|
+
const existing = child(root, name);
|
|
29
|
+
if (existing) return existing;
|
|
30
|
+
const node = root.ownerDocument!.createElementNS(spreadNs, name);
|
|
31
|
+
const index = collections.indexOf(name);
|
|
32
|
+
const next = children(root).find(entry => collections.indexOf(entry.localName ?? "") > index);
|
|
33
|
+
root.insertBefore(node, next ?? null);
|
|
34
|
+
return node;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param root - Style sheet element.
|
|
39
|
+
* @param name - Indexed collection.
|
|
40
|
+
* @param tag - One collection item.
|
|
41
|
+
* @returns Original records and indexes of appended derived records.
|
|
42
|
+
*/
|
|
43
|
+
function indexedStyles(root: Element, name: string, tag: string) {
|
|
44
|
+
const collection = ensureCollection(root, name);
|
|
45
|
+
const nodes = children(collection, tag);
|
|
46
|
+
const serializer = new XMLSerializer();
|
|
47
|
+
const indexes = new Map(nodes.map((entry, index) => [serializer.serializeToString(entry), index]));
|
|
48
|
+
return {
|
|
49
|
+
nodes,
|
|
50
|
+
/** @param entry - Derived style. @returns Shared style index. */
|
|
51
|
+
add(entry: Element): number {
|
|
52
|
+
const key = serializer.serializeToString(entry);
|
|
53
|
+
const found = indexes.get(key);
|
|
54
|
+
if (found !== undefined) return found;
|
|
55
|
+
const index = nodes.length;
|
|
56
|
+
collection.appendChild(entry);
|
|
57
|
+
nodes.push(entry);
|
|
58
|
+
indexes.set(key, index);
|
|
59
|
+
collection.setAttribute("count", String(nodes.length));
|
|
60
|
+
return index;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @param bytes - Original styles, if the workbook owns them.
|
|
67
|
+
* @param path - Name of the package part.
|
|
68
|
+
* @param checkboxComplement - Known mapper index for checkbox styles.
|
|
69
|
+
* @returns Style part and registration of overrides relative to the original indices.
|
|
70
|
+
*/
|
|
71
|
+
export function createXlsxStyleWriter(bytes: Uint8Array | undefined, path: string, checkboxComplement?: number) {
|
|
72
|
+
const document = parsePart(bytes ?? strToU8(initialStyles), path);
|
|
73
|
+
const root = rootOf(document, spreadNs, "styleSheet");
|
|
74
|
+
const fonts = indexedStyles(root, "fonts", "font");
|
|
75
|
+
const fills = indexedStyles(root, "fills", "fill");
|
|
76
|
+
const borders = indexedStyles(root, "borders", "border");
|
|
77
|
+
const xfs = indexedStyles(root, "cellXfs", "xf");
|
|
78
|
+
let differentials: ReturnType<typeof indexedStyles> | undefined;
|
|
79
|
+
const bases = children(child(root, "cellStyleXfs") ?? root, "xf");
|
|
80
|
+
const numbers = new Map([...builtinNumberFormats].map(([id, name]) => [name, id]));
|
|
81
|
+
const custom = child(root, "numFmts");
|
|
82
|
+
let nextNumberId = 164;
|
|
83
|
+
for (const entry of custom ? children(custom, "numFmt") : []) {
|
|
84
|
+
const id = readIndex(entry, "numFmtId");
|
|
85
|
+
const code = entry.getAttribute("formatCode");
|
|
86
|
+
if (id !== undefined && code) {
|
|
87
|
+
for (const [builtin, index] of numbers) if (index === id && builtin !== code) numbers.delete(builtin);
|
|
88
|
+
numbers.set(code, id);
|
|
89
|
+
nextNumberId = Math.max(nextNumberId, id + 1);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const registered = new Map<string, number>();
|
|
93
|
+
|
|
94
|
+
/** @param code - Excel display code. @returns Built-in or registered custom id. */
|
|
95
|
+
function numberId(code: string): number {
|
|
96
|
+
if (code.toLowerCase() === "general") return 0;
|
|
97
|
+
const matched = numbers.get(code);
|
|
98
|
+
if (matched !== undefined) return matched;
|
|
99
|
+
const table = ensureCollection(root, "numFmts");
|
|
100
|
+
const node = document.createElementNS(spreadNs, "numFmt");
|
|
101
|
+
const id = nextNumberId++;
|
|
102
|
+
node.setAttribute("numFmtId", String(id));
|
|
103
|
+
node.setAttribute("formatCode", code);
|
|
104
|
+
table.appendChild(node);
|
|
105
|
+
table.setAttribute("count", String(children(table, "numFmt").length));
|
|
106
|
+
numbers.set(code, id);
|
|
107
|
+
return id;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** @param node - Source record. @param name - Expected node kind. @returns Safe independent record. */
|
|
111
|
+
function clone(node: Element | undefined, name: string): Element {
|
|
112
|
+
return node ? node.cloneNode(true) as Element : document.createElementNS(spreadNs, name);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** @param index - Original cellXfs index. @param patch - Authored overrides.
|
|
116
|
+
* @param checkbox - Explicit feature style change, when needed. @returns Derived index. */
|
|
117
|
+
function add(index: number, patch: WorkbookCellFormat, checkbox?: boolean): number {
|
|
118
|
+
const key = index + ":" + JSON.stringify(patch) + ":" + String(checkbox);
|
|
119
|
+
const prior = registered.get(key);
|
|
120
|
+
if (prior !== undefined) return prior;
|
|
121
|
+
const xf = clone(xfs.nodes[index] ?? xfs.nodes[0], "xf");
|
|
122
|
+
const base = bases[readIndex(xf, "xfId") ?? 0];
|
|
123
|
+
if ([patch.fontFamily, patch.fontSize, patch.bold, patch.italic, patch.underline, patch.strike, patch.color].some(value => value !== undefined)) {
|
|
124
|
+
const font = clone(fonts.nodes[appliedStyleIndex(xf, base, "fontId", "applyFont") ?? 0], "font");
|
|
125
|
+
writeXlsxFont(font, patch);
|
|
126
|
+
xf.setAttribute("fontId", String(fonts.add(font)));
|
|
127
|
+
xf.setAttribute("applyFont", "1");
|
|
128
|
+
}
|
|
129
|
+
if (patch.background !== undefined) {
|
|
130
|
+
xf.setAttribute("fillId", String(fills.add(xlsxFill(document, patch.background))));
|
|
131
|
+
xf.setAttribute("applyFill", "1");
|
|
132
|
+
}
|
|
133
|
+
if (patch.borders !== undefined) {
|
|
134
|
+
const border = clone(borders.nodes[appliedStyleIndex(xf, base, "borderId", "applyBorder") ?? 0], "border");
|
|
135
|
+
writeXlsxBorder(border, patch.borders);
|
|
136
|
+
xf.setAttribute("borderId", String(borders.add(border)));
|
|
137
|
+
xf.setAttribute("applyBorder", "1");
|
|
138
|
+
}
|
|
139
|
+
if (patch.horizontal !== undefined || patch.vertical !== undefined || patch.indent !== undefined || patch.wrap !== undefined || patch.shrinkToFit !== undefined) {
|
|
140
|
+
writeXlsxAlignment(xf, base && child(base, "alignment"), patch);
|
|
141
|
+
}
|
|
142
|
+
if (patch.numberFormat !== undefined) {
|
|
143
|
+
xf.setAttribute("numFmtId", String(numberId(patch.numberFormat)));
|
|
144
|
+
xf.setAttribute("applyNumberFormat", "1");
|
|
145
|
+
}
|
|
146
|
+
if (checkbox !== undefined) {
|
|
147
|
+
if (checkbox && checkboxComplement === undefined) throw new Error("XLSX 缺少复选框样式部件。");
|
|
148
|
+
writeXlsxComplement(xf, checkbox ? checkboxComplement! : null);
|
|
149
|
+
}
|
|
150
|
+
const result = xfs.add(xf);
|
|
151
|
+
registered.set(key, result);
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
document, add,
|
|
156
|
+
/** @param style - Incremental conditional style. @returns Stable differential style index. */
|
|
157
|
+
addDifferential(style: XlsxDifferentialStyle): number {
|
|
158
|
+
differentials ??= indexedStyles(root, "dxfs", "dxf");
|
|
159
|
+
return differentials.add(writeXlsxDifferential(document, style));
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { strFromU8, unzipSync } from "fflate";
|
|
2
|
+
import { expect, it } from "vitest";
|
|
3
|
+
import { openWorkbook, parseWorkbookRange, type WorkbookCommandCall, type WorkbookSnapshot, type WorkbookStructuredTable } from "@quirekit/workbook";
|
|
4
|
+
import { createXlsx, openXlsx } from "../index";
|
|
5
|
+
|
|
6
|
+
const range = parseWorkbookRange("data", "A1:B3");
|
|
7
|
+
const first: WorkbookStructuredTable = { id: "revenue", name: "Revenue", range, columns: ["Product", "Amount"],
|
|
8
|
+
header: true, totals: false, showFilter: true };
|
|
9
|
+
const second: WorkbookStructuredTable = { id: "flags", name: "Flags", range: parseWorkbookRange("data", "E1:E3"), columns: ["Flag"],
|
|
10
|
+
header: true, totals: false, showFilter: true };
|
|
11
|
+
const seed: WorkbookSnapshot = { version: 1, id: "conversion", name: "Conversion", revision: 0, structuredTables: [first, second], sheets: [
|
|
12
|
+
{ id: "data", name: "Data", cells: [
|
|
13
|
+
...["Product", "Amount", "Alpha", 7, "Beta", 12].map((value, index) => ({ row: Math.floor(index / 2), column: index % 2, input: { kind: "value" as const, value } })),
|
|
14
|
+
...["Flag", "Yes", "No"].map((value, row) => ({ row, column: 4, input: { kind: "value" as const, value } }))
|
|
15
|
+
] }, { id: "report", name: "Report", cells: [] }
|
|
16
|
+
] };
|
|
17
|
+
|
|
18
|
+
it("removes only converted native parts and permits structure editing after converting the last table", async () => {
|
|
19
|
+
const original = createXlsx(seed);
|
|
20
|
+
const file = openXlsx("Conversion", original);
|
|
21
|
+
const [revenue, flags] = file.snapshot.structuredTables!;
|
|
22
|
+
const sheetId = revenue!.range.sheetId;
|
|
23
|
+
const book = await openWorkbook(file.snapshot, { appearance: file.appearance, axisRestrictions: file.axisRestrictions, cellShiftRestrictions: file.cellShiftRestrictions });
|
|
24
|
+
/** @param id - Operation identity. @param command - Exact owner and A1 target. @returns Published receipt. */
|
|
25
|
+
const apply = (id: string, command: WorkbookCommandCall) => book.commit(book.prepare({ operationId: id, baseRevision: book.revision, commands: [command] }).id);
|
|
26
|
+
/** @param table - Still native definition. @returns The same operation used by the workbook UI. */
|
|
27
|
+
const convert = (table: WorkbookStructuredTable): WorkbookCommandCall => ({ name: "convertStructuredTableToRange", target: table.range, params: { id: table.id } });
|
|
28
|
+
try {
|
|
29
|
+
const sourceParts = unzipSync(original);
|
|
30
|
+
const header = book.readFormat({ sheetId, row: 0, column: 0 });
|
|
31
|
+
expect(book.axisRestriction(sheetId)).toMatch(/先将表转换为区域/u);
|
|
32
|
+
await apply("first", convert(revenue!));
|
|
33
|
+
expect(book.axisRestriction(sheetId)).toMatch(/先将表转换为区域/u);
|
|
34
|
+
const one = unzipSync(file.write(book.snapshot()));
|
|
35
|
+
expect(one["xl/tables/table1.xml"]).toBeUndefined();
|
|
36
|
+
expect(one["xl/tables/table2.xml"]).toEqual(sourceParts["xl/tables/table2.xml"]);
|
|
37
|
+
expect(strFromU8(one["xl/worksheets/sheet1.xml"]!)).toContain('<tableParts count="1">');
|
|
38
|
+
expect(strFromU8(one["xl/worksheets/_rels/sheet1.xml.rels"]!)).not.toContain("table1.xml");
|
|
39
|
+
expect(strFromU8(one["[Content_Types].xml"]!)).not.toContain("table1.xml");
|
|
40
|
+
expect(one["xl/worksheets/sheet2.xml"]).toEqual(sourceParts["xl/worksheets/sheet2.xml"]);
|
|
41
|
+
|
|
42
|
+
await apply("last", convert(flags!));
|
|
43
|
+
expect(book.snapshot().structuredTables).toEqual([]);
|
|
44
|
+
expect(book.axisRestriction(sheetId)).toBeUndefined();
|
|
45
|
+
const checkpoint = await openWorkbook(book.snapshot(), { appearance: file.appearance });
|
|
46
|
+
try {
|
|
47
|
+
expect(checkpoint.structuredTableAt({ sheetId, row: 0, column: 0 })).toBeUndefined();
|
|
48
|
+
expect(checkpoint.readFormat({ sheetId, row: 0, column: 0 })).toEqual(header);
|
|
49
|
+
} finally { await checkpoint.close(); }
|
|
50
|
+
await apply("row", { name: "insertRows", target: parseWorkbookRange(sheetId, "A2"), params: { position: "before" } });
|
|
51
|
+
const bytes = file.write(book.snapshot());
|
|
52
|
+
const plain = unzipSync(bytes);
|
|
53
|
+
expect(Object.keys(plain).filter(path => path.includes("/tables/"))).toEqual([]);
|
|
54
|
+
expect(strFromU8(plain["xl/worksheets/sheet1.xml"]!)).not.toContain("tableParts");
|
|
55
|
+
expect(plain["xl/worksheets/_rels/sheet1.xml.rels"]).toBeUndefined();
|
|
56
|
+
const reopened = openXlsx("Plain", bytes);
|
|
57
|
+
expect(reopened.restrictions).toEqual([]);
|
|
58
|
+
expect(reopened.snapshot.sheets[0]?.cells).toContainEqual({ row: 2, column: 1, input: { kind: "value", value: 7 } });
|
|
59
|
+
|
|
60
|
+
await apply("copy", { name: "duplicateWorksheet", target: parseWorkbookRange(sheetId, "A1"), params: { name: "Copy" } });
|
|
61
|
+
const copied = openXlsx("With copy", file.write(book.snapshot()));
|
|
62
|
+
expect(copied.restrictions).toEqual([]);
|
|
63
|
+
expect(copied.snapshot.structuredTables ?? []).toEqual([]);
|
|
64
|
+
expect(copied.snapshot.sheets.find(sheet => sheet.name === "Copy")?.cells)
|
|
65
|
+
.toContainEqual(expect.objectContaining({ row: 2, column: 1, input: { kind: "value", value: 7 } }));
|
|
66
|
+
await book.undo("undo-copy");
|
|
67
|
+
await book.undo("undo-row");
|
|
68
|
+
await book.undo("undo-last");
|
|
69
|
+
expect(book.axisRestriction(sheetId)).toMatch(/先将表转换为区域/u);
|
|
70
|
+
await book.undo("undo-first");
|
|
71
|
+
expect(file.write(book.snapshot())).toEqual(original);
|
|
72
|
+
} finally { await book.close(); }
|
|
73
|
+
});
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { isWorkbookDefinedName, type WorkbookSourceTable, type WorkbookStructuredTableSorts } from "@quirekit/workbook";
|
|
3
|
+
import { isXlsxRevisionAttribute, xlsxFilterUidNs, xlsxTableColumnUidNs } from "../opc/revision";
|
|
4
|
+
import { hasKnownAttributes, hasKnownChildren } from "../opc/shape";
|
|
5
|
+
import { child, children, readIndex, spreadNs } from "../opc/xml";
|
|
6
|
+
import { decodeXlsxText } from "../worksheet/text";
|
|
7
|
+
import { isEmptyXlsxFilterExtension, wpsFilterNamespace } from "../worksheet/filters/rules";
|
|
8
|
+
|
|
9
|
+
// These formatting attributes describe passive style data. The package writer retains their exact bytes.
|
|
10
|
+
const styleFields = ["headerRowDxfId", "dataDxfId", "totalsRowDxfId", "headerRowBorderDxfId", "tableBorderDxfId",
|
|
11
|
+
"totalsRowBorderDxfId", "headerRowCellStyle", "dataCellStyle", "totalsRowCellStyle"];
|
|
12
|
+
|
|
13
|
+
/** @param root - Native table. @param fields - Its ordered columns. @param width - Size of the represented rectangle.
|
|
14
|
+
* @returns Valid unique headings for formula and header matching. */
|
|
15
|
+
export function readXlsxTableColumns(root: Element, fields: Element, width: number): readonly string[] | undefined {
|
|
16
|
+
if (!isWorkbookDefinedName(root.getAttribute("displayName") ?? root.getAttribute("name") ?? "") || fields.namespaceURI !== spreadNs) return;
|
|
17
|
+
const columns = children(fields);
|
|
18
|
+
if (columns.length !== width || fields.hasAttribute("count") && readIndex(fields, "count") !== width) return;
|
|
19
|
+
const names = new Set<string>(), ids = new Set<number>();
|
|
20
|
+
const headers: string[] = [];
|
|
21
|
+
for (const field of columns) {
|
|
22
|
+
const id = readIndex(field, "id"), name = decodeXlsxText(field.getAttribute("name") ?? "");
|
|
23
|
+
const folded = name.toUpperCase();
|
|
24
|
+
if (field.namespaceURI !== spreadNs || field.localName !== "tableColumn" || !id || ids.has(id)
|
|
25
|
+
|| !name.trim() || name.length > 255 || names.has(folded)) return;
|
|
26
|
+
names.add(folded);
|
|
27
|
+
ids.add(id);
|
|
28
|
+
headers.push(name);
|
|
29
|
+
}
|
|
30
|
+
return headers;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param node - Native column criterion. @param names - Supported attributes. @param flags - Attributes with Boolean values.
|
|
34
|
+
* @returns Whether this node can be rewritten without discarding any attributes. */
|
|
35
|
+
function filterAttributes(node: Element, names: readonly string[], flags: readonly string[] = []): boolean {
|
|
36
|
+
return node.namespaceURI === spreadNs && hasKnownAttributes(node, [...names, ...flags])
|
|
37
|
+
&& flags.every(flag => !node.hasAttribute(flag) || ["0", "1", "false", "true"].includes(node.getAttribute(flag) ?? ""));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** @param filter - Parsed table AutoFilter. @param managedSort - Whether the nested sort was decoded in full.
|
|
41
|
+
* @returns Whether every child belongs to the native filter writer. */
|
|
42
|
+
function supportsTableFilter(filter: Element, managedSort: boolean): boolean {
|
|
43
|
+
if (filter.namespaceURI !== spreadNs || Array.from(filter.attributes).some(attribute =>
|
|
44
|
+
attribute.namespaceURI !== "http://www.w3.org/2000/xmlns/" && !isXlsxRevisionAttribute(attribute, xlsxFilterUidNs) && (attribute.namespaceURI
|
|
45
|
+
? attribute.namespaceURI !== wpsFilterNamespace || attribute.localName !== "filterBottomFollowUsedRange" || attribute.value !== "0"
|
|
46
|
+
: attribute.name !== "ref"))) return false;
|
|
47
|
+
return children(filter).every(column => {
|
|
48
|
+
if (isEmptyXlsxFilterExtension(column)) return true;
|
|
49
|
+
if (managedSort && column.localName === "sortState") return true;
|
|
50
|
+
if (column.localName !== "filterColumn" || !filterAttributes(column, ["colId"], ["hiddenButton", "showButton"])) return false;
|
|
51
|
+
const criteria = children(column);
|
|
52
|
+
if (!criteria.length) return true;
|
|
53
|
+
const node = criteria[0]!;
|
|
54
|
+
// These conditions reach the writer only after the native filter reader validates the entire selection.
|
|
55
|
+
if (["colorFilter", "dynamicFilter", "iconFilter", "AlternateContent"].includes(node.localName ?? "")) return true;
|
|
56
|
+
if (criteria.length !== 1) return false;
|
|
57
|
+
if (node.localName === "filters") {
|
|
58
|
+
return filterAttributes(node, ["calendarType"], ["blank"]) && children(node).every(value => hasKnownChildren(value, [])
|
|
59
|
+
&& (value.localName === "filter" ? filterAttributes(value, ["val"])
|
|
60
|
+
: value.localName === "dateGroupItem" && filterAttributes(value, ["dateTimeGrouping", "year", "month", "day"])));
|
|
61
|
+
}
|
|
62
|
+
if (node.localName === "customFilters") {
|
|
63
|
+
return filterAttributes(node, [], ["and"]) && children(node).every(value =>
|
|
64
|
+
value.localName === "customFilter" && filterAttributes(value, ["operator", "val"]) && hasKnownChildren(value, []));
|
|
65
|
+
}
|
|
66
|
+
return node.localName === "top10" && hasKnownChildren(node, [])
|
|
67
|
+
&& filterAttributes(node, ["val", "filterVal"], ["top", "percent"]);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param root - Table definition intact in the package. @param layout - Parsed ranges, headers and native filtering.
|
|
72
|
+
* @param sorts - Fully decoded sort conditions by native owner.
|
|
73
|
+
* @returns Whether the supported changes leave all of the table's active state valid. */
|
|
74
|
+
export function xlsxTableAllowsDataWrites(root: Element, layout: WorkbookSourceTable, sorts?: WorkbookStructuredTableSorts): boolean {
|
|
75
|
+
if (!layout.columns || !hasKnownAttributes(root, ["id", "name", "displayName", "ref", "tableType",
|
|
76
|
+
"headerRowCount", "totalsRowCount", "totalsRowShown", "insertRow", "insertRowShift", "published", ...styleFields], false, attribute => isXlsxRevisionAttribute(attribute, xlsxFilterUidNs))
|
|
77
|
+
|| (root.getAttribute("tableType") || "worksheet") !== "worksheet"
|
|
78
|
+
|| !hasKnownChildren(root, ["autoFilter", "tableColumns", "tableStyleInfo", ...(sorts?.table ? ["sortState"] : [])])) return false;
|
|
79
|
+
const fields = child(root, "tableColumns")!;
|
|
80
|
+
if (!hasKnownAttributes(fields, ["count"]) || children(fields).some(field =>
|
|
81
|
+
!hasKnownAttributes(field, ["id", "name", "totalsRowLabel", "totalsRowFunction", ...styleFields], false,
|
|
82
|
+
attribute => isXlsxRevisionAttribute(attribute, xlsxTableColumnUidNs))
|
|
83
|
+
|| !hasKnownChildren(field, ["totalsRowFormula"]) || children(field, "totalsRowFormula").length > 1)) return false;
|
|
84
|
+
const filter = child(root, "autoFilter");
|
|
85
|
+
if (filter && (!layout.filter || !supportsTableFilter(filter, Boolean(sorts?.filter)))) return false;
|
|
86
|
+
const style = child(root, "tableStyleInfo");
|
|
87
|
+
return !style || (hasKnownChildren(style, [])
|
|
88
|
+
&& hasKnownAttributes(style, ["name", "showFirstColumn", "showLastColumn", "showRowStripes", "showColumnStripes"]));
|
|
89
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { sameWorkbookAutoFilter, workbookStructuredTableFilterRange, type WorkbookStructuredTable } from "@quirekit/workbook";
|
|
3
|
+
import { preserveXlsxFilterUid } from "../opc/revision";
|
|
4
|
+
import { child, children, readIndex, spreadNs } from "../opc/xml";
|
|
5
|
+
import type { XlsxDifferentialStyle } from "../styles/types";
|
|
6
|
+
import { makeXlsxAutoFilter } from "../worksheet/filters/write";
|
|
7
|
+
|
|
8
|
+
/** @param root - Native table part. @param next - Current table layout. @param following - Next child in the schema sequence.
|
|
9
|
+
* @param addStyle - Registers filter colors. @param before - Preserved table definition, when imported.
|
|
10
|
+
* @returns Whether the filter owner was replaced or removed. */
|
|
11
|
+
export function writeXlsxTableFilter(root: Element, next: WorkbookStructuredTable, following: Element, addStyle: (style: XlsxDifferentialStyle) => number,
|
|
12
|
+
before?: WorkbookStructuredTable): boolean {
|
|
13
|
+
const previous = child(root, "autoFilter");
|
|
14
|
+
if (!next.showFilter) {
|
|
15
|
+
if (previous) root.removeChild(previous);
|
|
16
|
+
return Boolean(previous);
|
|
17
|
+
}
|
|
18
|
+
const range = workbookStructuredTableFilterRange(next);
|
|
19
|
+
const criteria = { range, columns: next.filter?.columns ?? [], hiddenRows: [] };
|
|
20
|
+
if (before && previous && sameWorkbookAutoFilter(criteria, {
|
|
21
|
+
range: workbookStructuredTableFilterRange(before), columns: before.filter?.columns ?? [], hiddenRows: []
|
|
22
|
+
})) return false;
|
|
23
|
+
|
|
24
|
+
const document = root.ownerDocument!;
|
|
25
|
+
const filter = makeXlsxAutoFilter(document, criteria, addStyle);
|
|
26
|
+
preserveXlsxFilterUid(previous, filter);
|
|
27
|
+
const indexed = new Map(children(filter, "filterColumn").map(node => [readIndex(node, "colId")!, node]));
|
|
28
|
+
if (previous && before) for (const entry of children(previous, "filterColumn")) {
|
|
29
|
+
const column = before.range.startColumn + readIndex(entry, "colId")! - range.startColumn;
|
|
30
|
+
if (column < 0 || column > range.endColumn - range.startColumn) continue;
|
|
31
|
+
const attrs = ["hiddenButton", "showButton"].filter(name => entry.hasAttribute(name));
|
|
32
|
+
if (!attrs.length) continue;
|
|
33
|
+
const target = indexed.get(column) ?? document.createElementNS(spreadNs, "filterColumn");
|
|
34
|
+
target.setAttribute("colId", String(column));
|
|
35
|
+
for (const name of attrs) target.setAttribute(name, entry.getAttribute(name)!);
|
|
36
|
+
indexed.set(column, target);
|
|
37
|
+
}
|
|
38
|
+
for (const [, node] of [...indexed].sort(([left], [right]) => left - right)) filter.appendChild(node);
|
|
39
|
+
if (previous) root.removeChild(previous);
|
|
40
|
+
root.insertBefore(filter, following);
|
|
41
|
+
return true;
|
|
42
|
+
}
|