@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
package/src/opc/xml.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { DOMParser, XMLSerializer, normalizeLineEndings, onErrorStopParsing, type Document, type Element } from "@xmldom/xmldom";
|
|
2
|
+
import { strFromU8, strToU8 } from "fflate";
|
|
3
|
+
|
|
4
|
+
/** SpreadsheetML worksheet and workbook namespace. */
|
|
5
|
+
export const spreadNs = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
|
6
|
+
|
|
7
|
+
/** Namespace of spreadsheet relationship attributes. */
|
|
8
|
+
export const relationshipNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
|
9
|
+
|
|
10
|
+
/** Namespace used at the root of an OPC .rels part. */
|
|
11
|
+
export const packageRelationshipNs = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
12
|
+
|
|
13
|
+
/** Namespace used at the root of the OPC content type manifest. */
|
|
14
|
+
export const contentTypeNs = "http://schemas.openxmlformats.org/package/2006/content-types";
|
|
15
|
+
|
|
16
|
+
/** @param bytes - Original XML part. @param name - Part name for diagnostics. @returns XML accepted by the package policy. */
|
|
17
|
+
export function readXlsxXmlPartText(bytes: Uint8Array | undefined, name: string): string {
|
|
18
|
+
if (!bytes) throw new Error(`XLSX 缺少部件 ${name}。`);
|
|
19
|
+
const xml = strFromU8(bytes);
|
|
20
|
+
if (/<!DOCTYPE\b/i.test(xml)) throw new Error(`XLSX 部件 ${name} 包含不支持的文档类型声明。`);
|
|
21
|
+
return xml;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @param xml - XML text after checking the part policy. @param name - Part name for diagnostics. @returns Portable XML document. */
|
|
25
|
+
function parsePortableXml(xml: string, name: string): Document {
|
|
26
|
+
try {
|
|
27
|
+
return new DOMParser({ onError: onErrorStopParsing }).parseFromString(xml, "application/xml");
|
|
28
|
+
} catch (cause) {
|
|
29
|
+
throw new Error(`无法解析 XLSX 部件 ${name}。`, { cause });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param bytes - Part to parse. @param name - Part name for diagnostics. @returns Parsed XML. */
|
|
34
|
+
export function parsePart(bytes: Uint8Array | undefined, name: string): Document {
|
|
35
|
+
return parsePortableXml(readXlsxXmlPartText(bytes, name), name);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Reads a worksheet using the browser's compact native DOM when available.
|
|
40
|
+
* @param bytes - Original worksheet XML bytes. @param name - Worksheet part name.
|
|
41
|
+
* @returns Worksheet root for import readers. The writer separately opens the original part.
|
|
42
|
+
*/
|
|
43
|
+
export function parseWorksheetPart(bytes: Uint8Array | undefined, name: string): Element {
|
|
44
|
+
return parseXlsxWorksheetXml(readXlsxXmlPartText(bytes, name), name);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param xml - Checked worksheet XML or a bounded slice preserving its namespace context.
|
|
48
|
+
* @param name - Part name for diagnostics. @returns A worksheet root from the available parser. */
|
|
49
|
+
export function parseXlsxWorksheetXml(xml: string, name: string): Element {
|
|
50
|
+
if (typeof globalThis.DOMParser === "function") {
|
|
51
|
+
try {
|
|
52
|
+
const document = new globalThis.DOMParser().parseFromString(normalizeLineEndings(xml), "application/xml");
|
|
53
|
+
const root = document.documentElement;
|
|
54
|
+
if (root?.localName === "worksheet" && root.namespaceURI === spreadNs
|
|
55
|
+
&& document.getElementsByTagNameNS("*", "parsererror").length === 0) {
|
|
56
|
+
// Both DOM implementations expose the standard element properties used by the import readers.
|
|
57
|
+
return root as unknown as Element;
|
|
58
|
+
}
|
|
59
|
+
} catch {
|
|
60
|
+
// A browser host can restrict string-based DOM parsing. The portable parser still checks the same source.
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return rootOf(parsePortableXml(xml, name), spreadNs, "worksheet");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @param document - XML part to serialize.
|
|
68
|
+
* @returns UTF-8 part bytes.
|
|
69
|
+
*/
|
|
70
|
+
export function writePart(document: Document): Uint8Array {
|
|
71
|
+
return strToU8(new XMLSerializer().serializeToString(document));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @param node - Parent element.
|
|
76
|
+
* @param name - Optional child local name.
|
|
77
|
+
* @returns Direct children in source order.
|
|
78
|
+
*/
|
|
79
|
+
export function children(node: Element, name?: string): Element[] {
|
|
80
|
+
const items: Element[] = [];
|
|
81
|
+
for (let child = node.firstChild; child !== null; child = child.nextSibling) {
|
|
82
|
+
if (child.nodeType === 1 && (name === undefined || (child as Element).localName === name)) items.push(child as Element);
|
|
83
|
+
}
|
|
84
|
+
return items;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @param node - Parent element.
|
|
89
|
+
* @param name - Direct child local name.
|
|
90
|
+
* @returns First matching element.
|
|
91
|
+
*/
|
|
92
|
+
export function child(node: Element, name: string): Element | undefined {
|
|
93
|
+
for (let child = node.firstChild; child !== null; child = child.nextSibling) {
|
|
94
|
+
if (child.nodeType === 1 && (child as Element).localName === name) return child as Element;
|
|
95
|
+
}
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* @param node - XML node to check.
|
|
101
|
+
* @param namespace - Expected namespace.
|
|
102
|
+
* @param name - Expected root local name.
|
|
103
|
+
* @returns Valid document element.
|
|
104
|
+
*/
|
|
105
|
+
export function rootOf(node: Document, namespace: string, name: string): Element {
|
|
106
|
+
const root = node.documentElement;
|
|
107
|
+
if (root?.localName !== name || root.namespaceURI !== namespace) throw new Error(`不支持的 XLSX ${name} 部件。`);
|
|
108
|
+
return root;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** @param node - Optional XML element. @param key - Integer attribute. @returns A valid present nonnegative index. */
|
|
112
|
+
export function readIndex(node: Element | undefined, key: string): number | undefined {
|
|
113
|
+
const value = node?.getAttribute(key);
|
|
114
|
+
if (!value || !/^\d+$/u.test(value)) return undefined;
|
|
115
|
+
const number = Number(value);
|
|
116
|
+
return Number.isSafeInteger(number) ? number : undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** @param node - Optional XML element. @param key - Size attribute. @returns A finite positive dimension. */
|
|
120
|
+
export function readSize(node: Element | undefined, key: string): number | undefined {
|
|
121
|
+
const value = Number(node?.getAttribute(key));
|
|
122
|
+
return Number.isFinite(value) && value > 0 ? value : undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** @param value - OOXML boolean attribute. @returns Whether the attribute is explicitly true. */
|
|
126
|
+
export function isTrue(value: string | null | undefined): boolean {
|
|
127
|
+
return value === "1" || value === "true";
|
|
128
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { hasKnownAttributes } from "../opc/shape";
|
|
3
|
+
import { child, children, readIndex, spreadNs } from "../opc/xml";
|
|
4
|
+
|
|
5
|
+
const maxColumns = 16384;
|
|
6
|
+
const maxRows = 1048576;
|
|
7
|
+
|
|
8
|
+
/** @param cell - Native cell. @param row - Explicit parent row index, starting at one.
|
|
9
|
+
* @returns Its explicit column index or zero for inferred or invalid positions. */
|
|
10
|
+
function explicitColumn(cell: Element, row: number): number {
|
|
11
|
+
if (cell.namespaceURI !== spreadNs || cell.localName !== "c") return 0;
|
|
12
|
+
const match = /^([A-Z]{1,3})([1-9]\d{0,6})$/u.exec(cell.getAttribute("r") ?? "");
|
|
13
|
+
if (!match || Number(match[2]) !== row) return 0;
|
|
14
|
+
let column = 0;
|
|
15
|
+
for (const letter of match[1]!) column = column * 26 + letter.charCodeAt(0) - 64;
|
|
16
|
+
return column <= maxColumns ? column : 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param worksheet - Complete worksheet root. @returns Number of provably empty default cell records removed. */
|
|
20
|
+
export function removeXlsxEmptyCells(worksheet: Element): number {
|
|
21
|
+
const grid = child(worksheet, "sheetData");
|
|
22
|
+
if (!grid || grid.namespaceURI !== spreadNs) return 0;
|
|
23
|
+
const styled = new Uint8Array(maxColumns + 1);
|
|
24
|
+
for (const columns of children(worksheet, "cols")) for (const column of children(columns, "col")) {
|
|
25
|
+
if (!column.hasAttribute("style")) continue;
|
|
26
|
+
const first = readIndex(column, "min"), last = readIndex(column, "max");
|
|
27
|
+
if (!first || !last || first > last || last > maxColumns) return 0;
|
|
28
|
+
styled.fill(1, first, last + 1);
|
|
29
|
+
}
|
|
30
|
+
const rows = children(grid);
|
|
31
|
+
const positions = rows.map(row => row.namespaceURI === spreadNs && row.localName === "row" ? readIndex(row, "r") ?? 0 : 0);
|
|
32
|
+
const explicitRows = positions.every((row, index) => row > (positions[index - 1] ?? 0) && row <= maxRows);
|
|
33
|
+
let removed = 0;
|
|
34
|
+
for (const [index, row] of rows.entries()) {
|
|
35
|
+
const position = positions[index];
|
|
36
|
+
if (row.hasAttribute("s") || row.hasAttribute("customFormat")) continue;
|
|
37
|
+
if (!position || position > maxRows) continue;
|
|
38
|
+
const cells = children(row);
|
|
39
|
+
const indexes = cells.map(cell => explicitColumn(cell, position));
|
|
40
|
+
// A missing or inferred address can make a following cell depend on the preceding record.
|
|
41
|
+
if (indexes.some((column, i) => column <= (indexes[i - 1] ?? 0))) continue;
|
|
42
|
+
const previous = removed;
|
|
43
|
+
for (const [index, cell] of cells.entries()) {
|
|
44
|
+
if (styled[indexes[index]!] || cell.hasChildNodes() || !hasKnownAttributes(cell, ["r", "t", "s"])) continue;
|
|
45
|
+
if (cell.hasAttribute("s") && cell.getAttribute("s") !== "0" || cell.hasAttribute("t") && cell.getAttribute("t") !== "n") continue;
|
|
46
|
+
row.removeChild(cell);
|
|
47
|
+
removed++;
|
|
48
|
+
}
|
|
49
|
+
// A row carrying only its position is optional after cleanup if following rows also have explicit positions.
|
|
50
|
+
if (explicitRows && removed > previous && !row.hasChildNodes() && hasKnownAttributes(row, ["r"])) grid.removeChild(row);
|
|
51
|
+
}
|
|
52
|
+
return removed;
|
|
53
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
2
|
+
import type { Element } from "@xmldom/xmldom";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import type { WorkbookSnapshot } from "@quirekit/workbook";
|
|
5
|
+
import { createXlsx } from "../create";
|
|
6
|
+
import { openXlsx } from "../package/read";
|
|
7
|
+
import { child, children, parsePart, relationshipNs, rootOf, spreadNs, writePart } from "../opc/xml";
|
|
8
|
+
import { optimizeXlsx } from "./optimize";
|
|
9
|
+
|
|
10
|
+
const sheetPath = "xl/worksheets/sheet1.xml";
|
|
11
|
+
const stylesPath = "xl/styles.xml";
|
|
12
|
+
const ledger: WorkbookSnapshot = { version: 1, id: "ledger", name: "应收", revision: 0,
|
|
13
|
+
sheets: [{ id: "orders", name: "订单", cells: [] }, { id: "detail", name: "明细", visibility: "hidden", cells: [] }] };
|
|
14
|
+
|
|
15
|
+
/** @param extras - Additional package content to preserve. @returns Explicit native styles, cells and conditions. */
|
|
16
|
+
function fixture(extras: Record<string, Uint8Array> = {}) {
|
|
17
|
+
const provisional = createXlsx({ ...ledger, sheets: [{ ...ledger.sheets[0]!, formats: [{ row: 0, column: 0, format: { bold: true } }] }, ledger.sheets[1]!] });
|
|
18
|
+
const parts: Record<string, Uint8Array> = unzipSync(provisional);
|
|
19
|
+
const styles = parsePart(parts[stylesPath], stylesPath);
|
|
20
|
+
const stylesheet = rootOf(styles, spreadNs, "styleSheet");
|
|
21
|
+
const formats = child(stylesheet, "cellXfs")!;
|
|
22
|
+
const [normal, bold] = children(formats, "xf");
|
|
23
|
+
formats.appendChild(normal!.cloneNode(true));
|
|
24
|
+
formats.appendChild(bold!.cloneNode(true));
|
|
25
|
+
const currency = bold!.cloneNode(true) as Element;
|
|
26
|
+
currency.setAttribute("numFmtId", "2");
|
|
27
|
+
currency.setAttribute("applyNumberFormat", "1");
|
|
28
|
+
formats.appendChild(currency);
|
|
29
|
+
formats.setAttribute("count", "5");
|
|
30
|
+
const diff = child(stylesheet, "dxfs") ?? styles.createElementNS(spreadNs, "dxfs");
|
|
31
|
+
diff.setAttribute("count", "1");
|
|
32
|
+
diff.appendChild(styles.createElementNS(spreadNs, "dxf"));
|
|
33
|
+
if (!diff.parentNode) stylesheet.insertBefore(diff, child(stylesheet, "tableStyles") ?? null);
|
|
34
|
+
parts[stylesPath] = writePart(styles);
|
|
35
|
+
|
|
36
|
+
/** @param priority - Original rule evaluation order. @returns Static native condition. */
|
|
37
|
+
const comparison = (priority: number) => `<cfRule type="cellIs" dxfId="0" operator="greaterThan" priority="${priority}"><formula>5</formula></cfRule>`;
|
|
38
|
+
/** @param priority - Original rule evaluation order. @returns An expression with non-repeatable results. */
|
|
39
|
+
const volatile = (priority: number) => `<cfRule type="expression" dxfId="0" priority="${priority}"><formula>RAND()>0.5</formula></cfRule>`;
|
|
40
|
+
parts[sheetPath] = strToU8(`<worksheet xmlns="${spreadNs}"><dimension ref="A1:I100"/><cols><col min="5" max="5" style="3" width="14"/></cols>` +
|
|
41
|
+
'<sheetData><row r="1"><c r="A1" s="3" t="inlineStr"><is><t>0007</t></is></c><c r="B1"/><c r="C1" s="4"><f>2+3</f><v>5</v></c>' +
|
|
42
|
+
'<c r="D1" t="n"/><c r="E1"/><c r="F1" cm="1"/><c r="G1" s="3"/><c r="H1" s="0"/><c r="I1" t="inlineStr"><is><t/></is></c></row>' +
|
|
43
|
+
'<row r="2" s="3" customFormat="1" ht="30" customHeight="1"><c r="A2"/></row>' +
|
|
44
|
+
'<row r="3"><c r="A3"/><c><v>42</v></c></row><row r="100"><c r="G100"/></row></sheetData>' +
|
|
45
|
+
`<conditionalFormatting sqref="C1">${comparison(1)}${comparison(2)}${volatile(3)}${volatile(4)}</conditionalFormatting></worksheet>`);
|
|
46
|
+
return { ...parts, ...extras };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
it("compacts explicit default blanks, cell formats and static duplicate rules without moving data", () => {
|
|
50
|
+
const parts = fixture();
|
|
51
|
+
const original = zipSync(parts, { level: 0 });
|
|
52
|
+
const { optimized } = optimizeXlsx(original);
|
|
53
|
+
expect(optimized).toMatchObject({ emptyCells: 4, duplicateStyles: 2, duplicateRules: 1 });
|
|
54
|
+
expect(optimized!.bytes.length).toBeLessThan(original.length);
|
|
55
|
+
const reopened = unzipSync(optimized!.bytes);
|
|
56
|
+
const xml = strFromU8(reopened[sheetPath]!);
|
|
57
|
+
expect(xml).toContain('<dimension ref="A1:I100"');
|
|
58
|
+
expect(xml).toContain('<col min="5" max="5" style="1" width="14"');
|
|
59
|
+
expect(xml).toContain('<c r="A1" s="1" t="inlineStr"><is><t>0007</t></is></c>');
|
|
60
|
+
expect(xml).toContain('<c r="C1" s="2"><f>2+3</f><v>5</v></c>');
|
|
61
|
+
expect(xml).toContain('<c r="E1"/><c r="F1" cm="1"/><c r="G1" s="1"/><c r="I1" t="inlineStr">');
|
|
62
|
+
expect(xml).toContain('<row r="2" s="1" customFormat="1" ht="30" customHeight="1"><c r="A2"/></row>');
|
|
63
|
+
expect(xml).toContain('<row r="3"><c r="A3"/><c><v>42</v></c></row>');
|
|
64
|
+
expect(xml).not.toContain('<row r="100"');
|
|
65
|
+
expect(xml).not.toContain('priority="2"');
|
|
66
|
+
expect(xml.match(/RAND\(\)/gu)).toHaveLength(2);
|
|
67
|
+
expect(strFromU8(reopened[stylesPath]!)).toContain('<cellXfs count="3">');
|
|
68
|
+
expect(reopened["xl/workbook.xml"]).toEqual(parts["xl/workbook.xml"]);
|
|
69
|
+
expect(reopened["xl/worksheets/sheet2.xml"]).toEqual(parts["xl/worksheets/sheet2.xml"]);
|
|
70
|
+
const file = openXlsx("应收", optimized!.bytes);
|
|
71
|
+
expect(file.snapshot.sheets[0]!.cells.slice(0, 2).map(cell => cell.input)).toEqual([
|
|
72
|
+
{ kind: "value", value: "0007" }, { kind: "formula", formula: "=2+3" }
|
|
73
|
+
]);
|
|
74
|
+
expect(file.snapshot.sheets[1]!.visibility).toBe("hidden");
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("preserves opaque package data and avoids rewriting style indexes used by unknown parts", () => {
|
|
78
|
+
const parts = fixture({ "xl/vendor/opaque.xml": strToU8('<vendorData index="3"/>') });
|
|
79
|
+
const compact = optimizeXlsx(zipSync(parts, { level: 0 })).optimized!;
|
|
80
|
+
expect(compact.duplicateStyles).toBe(0);
|
|
81
|
+
expect(compact.emptyCells).toBe(4);
|
|
82
|
+
const result = unzipSync(compact.bytes);
|
|
83
|
+
expect(result[stylesPath]).toEqual(parts[stylesPath]);
|
|
84
|
+
expect(result["xl/vendor/opaque.xml"]).toEqual(parts["xl/vendor/opaque.xml"]);
|
|
85
|
+
expect(strFromU8(result[sheetPath]!)).toContain('<c r="A1" s="3"');
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("retains the row address marker when following rows have implicit positions", () => {
|
|
89
|
+
const parts = fixture();
|
|
90
|
+
const xml = strFromU8(parts[sheetPath]!);
|
|
91
|
+
parts[sheetPath] = strToU8(xml.replace("</sheetData>", '<row><c><v>99</v></c></row></sheetData>'));
|
|
92
|
+
const copy = optimizeXlsx(zipSync(parts, { level: 0 })).optimized!;
|
|
93
|
+
const result = strFromU8(unzipSync(copy.bytes)[sheetPath]!);
|
|
94
|
+
expect(result).toContain('<row r="100"/><row><c><v>99</v></c></row>');
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("protects stored style indexes when a worksheet relationship lies outside the directory", () => {
|
|
98
|
+
const other = "xl/worksheets/unlisted.xml";
|
|
99
|
+
const parts = fixture({ [other]: strToU8(`<worksheet xmlns="${spreadNs}"><sheetData><row r="1"><c r="A1" s="4"/></row></sheetData></worksheet>`) });
|
|
100
|
+
const links = "xl/_rels/workbook.xml.rels";
|
|
101
|
+
parts[links] = strToU8(strFromU8(parts[links]!).replace("</Relationships>",
|
|
102
|
+
`<Relationship Id="rIdUnlisted" Type="${relationshipNs}/worksheet" Target="worksheets/unlisted.xml"/></Relationships>`));
|
|
103
|
+
const result = optimizeXlsx(zipSync(parts, { level: 0 })).optimized!;
|
|
104
|
+
expect(result.duplicateStyles).toBe(0);
|
|
105
|
+
const files = unzipSync(result.bytes);
|
|
106
|
+
expect(files[stylesPath]).toEqual(parts[stylesPath]);
|
|
107
|
+
expect(files[other]).toEqual(parts[other]);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("reports signed packages and never replaces an equal or smaller archive", () => {
|
|
111
|
+
const signed = zipSync(fixture({ "_xmlsignatures/sig1.xml": strToU8("<signature/>") }), { level: 0 });
|
|
112
|
+
expect(optimizeXlsx(signed)).toEqual({ originalSize: signed.length, limitation: "signature" });
|
|
113
|
+
const macro = zipSync(fixture({ "xl/vbaProject.bin": new Uint8Array(5) }), { level: 0 });
|
|
114
|
+
expect(optimizeXlsx(macro)).toEqual({ originalSize: macro.length, limitation: "macro" });
|
|
115
|
+
const basic = zipSync(unzipSync(createXlsx(ledger)), { level: 9 });
|
|
116
|
+
expect(optimizeXlsx(basic)).toEqual({ originalSize: basic.length });
|
|
117
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { zipSync } from "fflate";
|
|
2
|
+
import { writePart } from "../opc/xml";
|
|
3
|
+
import { removeXlsxEmptyCells } from "./blanks";
|
|
4
|
+
import { readXlsxOptimizationPackage } from "./package";
|
|
5
|
+
import { removeXlsxConditionalDuplicates } from "./rules";
|
|
6
|
+
import { compactXlsxCellStyles } from "./styles";
|
|
7
|
+
import type { XlsxOptimizationPart, XlsxOptimizationResult } from "./types";
|
|
8
|
+
|
|
9
|
+
/** @param source - XLSX bytes from the approved source revision.
|
|
10
|
+
* @returns A strictly smaller native copy, or an explanation when original bytes should be used. */
|
|
11
|
+
export function optimizeXlsx(source: Uint8Array): XlsxOptimizationResult {
|
|
12
|
+
const originalSize = source.byteLength;
|
|
13
|
+
const scope = readXlsxOptimizationPackage(source);
|
|
14
|
+
if (scope.limitation) return { originalSize, limitation: scope.limitation };
|
|
15
|
+
const { parts, workbook, sheets, styles } = scope;
|
|
16
|
+
const changed = new Set<XlsxOptimizationPart>();
|
|
17
|
+
const duplicateStyles = styles ? compactXlsxCellStyles(workbook.root, styles, sheets, changed) : 0;
|
|
18
|
+
let emptyCells = 0, duplicateRules = 0;
|
|
19
|
+
for (const sheet of sheets) {
|
|
20
|
+
const cells = removeXlsxEmptyCells(sheet.root);
|
|
21
|
+
const rules = removeXlsxConditionalDuplicates(sheet.root);
|
|
22
|
+
emptyCells += cells;
|
|
23
|
+
duplicateRules += rules;
|
|
24
|
+
if (cells || rules) changed.add(sheet);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Retain a lossless repack option in case XML normalization offsets the structural savings.
|
|
28
|
+
const lossless = zipSync(parts, { level: 9 });
|
|
29
|
+
if (changed.size) {
|
|
30
|
+
const edited = { ...parts };
|
|
31
|
+
for (const { path, xml } of changed) edited[path] = writePart(xml);
|
|
32
|
+
const bytes = zipSync(edited, { level: 9 });
|
|
33
|
+
if (bytes.length < originalSize && bytes.length <= lossless.length) {
|
|
34
|
+
return { originalSize, optimized: { bytes, emptyCells, duplicateStyles, duplicateRules } };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (lossless.length < originalSize) {
|
|
38
|
+
return { originalSize, optimized: { bytes: lossless, emptyCells: 0, duplicateStyles: 0, duplicateRules: 0 } };
|
|
39
|
+
}
|
|
40
|
+
return { originalSize };
|
|
41
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { relationshipsPath, readRelationships } from "../opc/relationships";
|
|
2
|
+
import { openArchive } from "../opc/archive";
|
|
3
|
+
import { child, children, contentTypeNs, parsePart, relationshipNs, rootOf, spreadNs } from "../opc/xml";
|
|
4
|
+
import type { XlsxOptimizationPart, XlsxOptimizationResult } from "./types";
|
|
5
|
+
|
|
6
|
+
const manifestPath = "[Content_Types].xml";
|
|
7
|
+
const rootRelsPath = relationshipsPath("");
|
|
8
|
+
const workbookRole = relationshipNs + "/officeDocument";
|
|
9
|
+
const worksheetRole = relationshipNs + "/worksheet";
|
|
10
|
+
const simpleRelationships = new Set([
|
|
11
|
+
workbookRole, worksheetRole, ...["styles", "sharedStrings", "theme", "calcChain", "extended-properties", "custom-properties"].map(name => relationshipNs + "/" + name),
|
|
12
|
+
"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
/** @param parts - Expanded archive. @param path - Entry name from an actual workbook relationship.
|
|
16
|
+
* @param name - Root element role. @returns XML with its workbook namespace confirmed. */
|
|
17
|
+
function nativePart(parts: Record<string, Uint8Array>, path: string, name: string): XlsxOptimizationPart {
|
|
18
|
+
const xml = parsePart(parts[path], path);
|
|
19
|
+
return { path, xml, root: rootOf(xml, spreadNs, name) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param source - Input bytes. @returns Optimization scope derived from workbook relationships and part types. */
|
|
23
|
+
export function readXlsxOptimizationPackage(source: Uint8Array) {
|
|
24
|
+
const parts = openArchive(source);
|
|
25
|
+
const manifest = rootOf(parsePart(parts[manifestPath], manifestPath), contentTypeNs, "Types");
|
|
26
|
+
const rootRels = readRelationships(parsePart(parts[rootRelsPath], rootRelsPath), "");
|
|
27
|
+
const workbookPath = [...rootRels.values()].find(relation => relation.type === workbookRole)?.path;
|
|
28
|
+
if (!workbookPath) throw new Error("该文件没有可瘦身的 XLSX 工作簿。");
|
|
29
|
+
const mediaTypes = children(manifest).map(element => element.getAttribute("ContentType") ?? "");
|
|
30
|
+
const names = Object.keys(parts);
|
|
31
|
+
const signature = [...rootRels.values()].some(relation => /\/digital-signature\//iu.test(relation.type))
|
|
32
|
+
|| names.some(path => /^_xmlsignatures\//iu.test(path)) || mediaTypes.some(type => /digital-signature/iu.test(type));
|
|
33
|
+
const macros = names.some(path => /(?:vbaProject|\/macrosheets\/)/iu.test(path)) || mediaTypes.some(type => /macroEnabled|vbaProject/iu.test(type));
|
|
34
|
+
const limitation: XlsxOptimizationResult["limitation"] = signature ? "signature" : macros ? "macro" : undefined;
|
|
35
|
+
if (limitation) return { limitation };
|
|
36
|
+
|
|
37
|
+
const workbook = nativePart(parts, workbookPath, "workbook");
|
|
38
|
+
const relPath = relationshipsPath(workbookPath);
|
|
39
|
+
const relations = readRelationships(parsePart(parts[relPath], relPath), workbookPath);
|
|
40
|
+
const list = child(workbook.root, "sheets");
|
|
41
|
+
if (!list) throw new Error("XLSX 缺少工作表列表。");
|
|
42
|
+
const directory = children(list);
|
|
43
|
+
const paths = new Set<string>();
|
|
44
|
+
for (const element of directory) {
|
|
45
|
+
if (element.namespaceURI !== spreadNs || element.localName !== "sheet") continue;
|
|
46
|
+
const relation = relations.get(element.getAttributeNS(relationshipNs, "id") ?? "");
|
|
47
|
+
if (relation?.type === worksheetRole && relation.path) paths.add(relation.path);
|
|
48
|
+
}
|
|
49
|
+
const sheets = [...paths].map(path => nativePart(parts, path, "worksheet"));
|
|
50
|
+
|
|
51
|
+
// Renumbering global formats needs every potential consumer to be understood before any indexes change.
|
|
52
|
+
const known = new Set([manifestPath, rootRelsPath, relPath]);
|
|
53
|
+
const referencesKnown = [...rootRels.values(), ...relations.values()].every(({ path, type }) => {
|
|
54
|
+
if (!path || !simpleRelationships.has(type)) return false;
|
|
55
|
+
known.add(path);
|
|
56
|
+
return true;
|
|
57
|
+
});
|
|
58
|
+
const completeDirectory = sheets.length === directory.length && [...relations.values()].every(relation =>
|
|
59
|
+
relation.type !== worksheetRole || relation.path !== null && paths.has(relation.path));
|
|
60
|
+
const styleLinks = [...relations.values()].filter(relation => relation.type === relationshipNs + "/styles");
|
|
61
|
+
const stylePath = referencesKnown && completeDirectory && styleLinks.length === 1 && names.every(path => known.has(path))
|
|
62
|
+
? styleLinks[0]!.path : undefined;
|
|
63
|
+
const styles = stylePath ? nativePart(parts, stylePath, "styleSheet") : undefined;
|
|
64
|
+
return { parts, workbook, sheets, styles };
|
|
65
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { XMLSerializer, type Element } from "@xmldom/xmldom";
|
|
2
|
+
import { hasKnownAttributes } from "../opc/shape";
|
|
3
|
+
import { children, readIndex, spreadNs } from "../opc/xml";
|
|
4
|
+
|
|
5
|
+
const numeric = /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/u;
|
|
6
|
+
const staticRules = new Set(["cellIs", "duplicateValues", "uniqueValues", "top10", "aboveAverage"]);
|
|
7
|
+
const attributes = ["type", "dxfId", "priority", "stopIfTrue", "operator", "percent", "bottom", "rank", "aboveAverage", "equalAverage", "stdDev"];
|
|
8
|
+
|
|
9
|
+
/** @param group - Rule application region. @param rule - Native conditional condition.
|
|
10
|
+
* @param serializer - Standard XML serializer. @returns A key for comparable static rules, including their exact ranges. */
|
|
11
|
+
function staticRuleKey(group: Element, rule: Element, serializer: XMLSerializer): string | undefined {
|
|
12
|
+
if (!hasKnownAttributes(group, ["sqref"]) || group.namespaceURI !== spreadNs || rule.namespaceURI !== spreadNs
|
|
13
|
+
|| !group.getAttribute("sqref") || !hasKnownAttributes(rule, attributes) || readIndex(rule, "dxfId") === undefined) return;
|
|
14
|
+
const type = rule.getAttribute("type") ?? "";
|
|
15
|
+
if (!staticRules.has(type)) return;
|
|
16
|
+
const members = children(rule);
|
|
17
|
+
if (type === "cellIs") {
|
|
18
|
+
if (!members.length || members.some(member => member.namespaceURI !== spreadNs || member.localName !== "formula"
|
|
19
|
+
|| !hasKnownAttributes(member, []) || children(member).length || !numeric.test(member.textContent?.trim() ?? ""))) return;
|
|
20
|
+
} else if (members.length) return;
|
|
21
|
+
const body = rule.cloneNode(true) as Element;
|
|
22
|
+
body.removeAttribute("priority");
|
|
23
|
+
return group.getAttribute("sqref") + "\n" + serializer.serializeToString(body);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param worksheet - Native sheet XML. @returns Number of redundant adjacent static rules discarded. */
|
|
27
|
+
export function removeXlsxConditionalDuplicates(worksheet: Element): number {
|
|
28
|
+
if (worksheet.getElementsByTagNameNS("*", "extLst").length || worksheet.getElementsByTagNameNS("*", "AlternateContent").length) return 0;
|
|
29
|
+
const groups = children(worksheet, "conditionalFormatting");
|
|
30
|
+
const entries = groups.flatMap(group => children(group, "cfRule").map(rule => ({ group, rule, priority: readIndex(rule, "priority") ?? 0 })));
|
|
31
|
+
if (entries.some(entry => entry.priority < 1) || new Set(entries.map(entry => entry.priority)).size !== entries.length) return 0;
|
|
32
|
+
const serializer = new XMLSerializer();
|
|
33
|
+
let previous: string | undefined;
|
|
34
|
+
let removed = 0;
|
|
35
|
+
// Only adjacent evaluations of the same deterministic rule are redundant. Keep original priorities for other rules.
|
|
36
|
+
for (const { group, rule } of entries.sort((a, b) => a.priority - b.priority)) {
|
|
37
|
+
const key = staticRuleKey(group, rule, serializer);
|
|
38
|
+
if (key !== undefined && key === previous) {
|
|
39
|
+
group.removeChild(rule);
|
|
40
|
+
if (!children(group).length) worksheet.removeChild(group);
|
|
41
|
+
removed++;
|
|
42
|
+
}
|
|
43
|
+
previous = key;
|
|
44
|
+
}
|
|
45
|
+
return removed;
|
|
46
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { XMLSerializer, type Element } from "@xmldom/xmldom";
|
|
2
|
+
import { hasKnownAttributes } from "../opc/shape";
|
|
3
|
+
import { child, children, readIndex, relationshipNs, spreadNs } from "../opc/xml";
|
|
4
|
+
import type { XlsxOptimizationPart } from "./types";
|
|
5
|
+
|
|
6
|
+
const xmlns = "http://www.w3.org/2000/xmlns/";
|
|
7
|
+
const xml = "http://www.w3.org/XML/1998/namespace";
|
|
8
|
+
const compatibility = "http://schemas.openxmlformats.org/markup-compatibility/2006";
|
|
9
|
+
|
|
10
|
+
/** @param root - Workbook, stylesheet, or ordinary worksheet. @returns Whether its style references are standard SpreadsheetML. */
|
|
11
|
+
function hasKnownStyleConsumers(root: Element): boolean {
|
|
12
|
+
const pending = [root];
|
|
13
|
+
while (pending.length) {
|
|
14
|
+
const element = pending.pop()!;
|
|
15
|
+
if (element.namespaceURI !== spreadNs || element.localName === "extLst") return false;
|
|
16
|
+
for (const attribute of Array.from(element.attributes)) {
|
|
17
|
+
const ns = attribute.namespaceURI;
|
|
18
|
+
if (ns && ns !== xmlns && ns !== xml && ns !== relationshipNs
|
|
19
|
+
&& !(ns === compatibility && attribute.localName === "Ignorable")) return false;
|
|
20
|
+
}
|
|
21
|
+
for (const member of children(element)) pending.push(member);
|
|
22
|
+
}
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param sheet - Native worksheet. @returns Its cell, row, and column style index owners. */
|
|
27
|
+
function* styleReferences(sheet: Element): Iterable<[element: Element, attribute: string]> {
|
|
28
|
+
for (const cols of children(sheet, "cols")) for (const col of children(cols, "col")) {
|
|
29
|
+
if (col.hasAttribute("style")) yield [col, "style"];
|
|
30
|
+
}
|
|
31
|
+
const data = child(sheet, "sheetData");
|
|
32
|
+
for (const row of data ? children(data, "row") : []) {
|
|
33
|
+
if (row.hasAttribute("s")) yield [row, "s"];
|
|
34
|
+
for (const cell of children(row, "c")) if (cell.hasAttribute("s")) yield [cell, "s"];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @param workbook - Workbook metadata whose extensions may refer to styles. @param style - Package style definitions.
|
|
39
|
+
* @param sheets - All ordinary worksheets in the workbook. @param changed - XML entries that now require serialization.
|
|
40
|
+
* @returns Exact duplicate records compacted after validating every reference. */
|
|
41
|
+
export function compactXlsxCellStyles(workbook: Element, style: XlsxOptimizationPart, sheets: readonly XlsxOptimizationPart[], changed: Set<XlsxOptimizationPart>): number {
|
|
42
|
+
const table = child(style.root, "cellXfs");
|
|
43
|
+
if (!table || table.namespaceURI !== spreadNs || !hasKnownAttributes(table, ["count"])) return 0;
|
|
44
|
+
const formats = children(table);
|
|
45
|
+
if (!formats.length || formats.some(format => format.localName !== "xf" || format.namespaceURI !== spreadNs)) return 0;
|
|
46
|
+
const records = new Map<string, number>();
|
|
47
|
+
const duplicates: Element[] = [];
|
|
48
|
+
const serializer = new XMLSerializer();
|
|
49
|
+
const indexMap = formats.map(format => {
|
|
50
|
+
const key = serializer.serializeToString(format);
|
|
51
|
+
const registered = records.get(key);
|
|
52
|
+
if (registered !== undefined) { duplicates.push(format); return registered; }
|
|
53
|
+
const index = records.size;
|
|
54
|
+
records.set(key, index);
|
|
55
|
+
return index;
|
|
56
|
+
});
|
|
57
|
+
if (!duplicates.length || !hasKnownStyleConsumers(workbook) || !hasKnownStyleConsumers(style.root)
|
|
58
|
+
|| sheets.some(sheet => !hasKnownStyleConsumers(sheet.root))) return 0;
|
|
59
|
+
|
|
60
|
+
// Collect updates without changing the XML so a malformed or opaque reference leaves the index table untouched.
|
|
61
|
+
const updates: { sheet: XlsxOptimizationPart; element: Element; attribute: string; value: number }[] = [];
|
|
62
|
+
for (const sheet of sheets) for (const [element, attribute] of styleReferences(sheet.root)) {
|
|
63
|
+
const index = readIndex(element, attribute);
|
|
64
|
+
const value = index === undefined ? undefined : indexMap[index];
|
|
65
|
+
if (value === undefined) return 0;
|
|
66
|
+
if (value !== index) updates.push({ sheet, element, attribute, value });
|
|
67
|
+
}
|
|
68
|
+
for (const { sheet, element, attribute, value } of updates) {
|
|
69
|
+
element.setAttribute(attribute, String(value));
|
|
70
|
+
changed.add(sheet);
|
|
71
|
+
}
|
|
72
|
+
for (const duplicate of duplicates) table.removeChild(duplicate);
|
|
73
|
+
table.setAttribute("count", String(records.size));
|
|
74
|
+
changed.add(style);
|
|
75
|
+
return duplicates.length;
|
|
76
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Document, Element } from "@xmldom/xmldom";
|
|
2
|
+
|
|
3
|
+
/** A smaller XLSX produced from exactly one source archive. */
|
|
4
|
+
export interface XlsxOptimizedCopy {
|
|
5
|
+
/** Complete optimized archive. */
|
|
6
|
+
readonly bytes: Uint8Array;
|
|
7
|
+
/** Removed unformatted blank cell records. */
|
|
8
|
+
readonly emptyCells: number;
|
|
9
|
+
/** Duplicate cell format definitions merged into their first occurrence. */
|
|
10
|
+
readonly duplicateStyles: number;
|
|
11
|
+
/** Redundant static conditional formatting rules removed. */
|
|
12
|
+
readonly duplicateRules: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Result of analyzing and encoding an XLSX copy. */
|
|
16
|
+
export interface XlsxOptimizationResult {
|
|
17
|
+
/** Size of the input archive in bytes. */
|
|
18
|
+
readonly originalSize: number;
|
|
19
|
+
/** Verified-smaller output, if this source has recoverable space. */
|
|
20
|
+
readonly optimized?: XlsxOptimizedCopy;
|
|
21
|
+
/** Package feature that requires retaining the original file. */
|
|
22
|
+
readonly limitation?: "signature" | "macro";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Identified XML and its original path in an OPC package. */
|
|
26
|
+
export interface XlsxOptimizationPart {
|
|
27
|
+
/** ZIP entry name. */
|
|
28
|
+
readonly path: string;
|
|
29
|
+
/** Parsed source that can be edited privately. */
|
|
30
|
+
readonly xml: Document;
|
|
31
|
+
/** Validated root element. */
|
|
32
|
+
readonly root: Element;
|
|
33
|
+
}
|