@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,70 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookColumn, type WorkbookAxisCopyLayout } from "@quirekit/workbook";
|
|
3
|
+
import { child, children, readIndex, spreadNs } from "../opc/xml";
|
|
4
|
+
import { appendOrdered, indexCells, indexRows } from "./positions";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @param worksheet - Native worksheet after the structural gap has been opened.
|
|
8
|
+
* @param data - Its cell data in the new coordinate space.
|
|
9
|
+
* @param layout - Detached native style basis at the time of the copy.
|
|
10
|
+
*/
|
|
11
|
+
export function writeXlsxCopiedAxis(worksheet: Element, data: Element, layout: WorkbookAxisCopyLayout): void {
|
|
12
|
+
const document = worksheet.ownerDocument!;
|
|
13
|
+
const rows = indexRows(data);
|
|
14
|
+
const changedCells = new Map<number, Map<number, Element>>();
|
|
15
|
+
|
|
16
|
+
/** @param index - Zero-based output row. @returns The row node, allocating it for a copied style if needed. */
|
|
17
|
+
function rowAt(index: number): Element {
|
|
18
|
+
let row = rows.get(index);
|
|
19
|
+
if (!row) {
|
|
20
|
+
row = document.createElementNS(spreadNs, "row");
|
|
21
|
+
row.setAttribute("r", String(index + 1));
|
|
22
|
+
rows.set(index, row);
|
|
23
|
+
}
|
|
24
|
+
return row;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Values and formula caches will be written from the committed workbook. Only the native style basis is installed here.
|
|
28
|
+
for (const { index, appearance: { size, autoHeight, hidden, style } } of layout.rows ?? []) {
|
|
29
|
+
const row = rowAt(index);
|
|
30
|
+
if (size !== undefined) {
|
|
31
|
+
row.setAttribute("ht", String(size * 3 / 4));
|
|
32
|
+
if (!autoHeight) row.setAttribute("customHeight", "1");
|
|
33
|
+
}
|
|
34
|
+
if (hidden) row.setAttribute("hidden", "1");
|
|
35
|
+
if (style !== undefined) {
|
|
36
|
+
row.setAttribute("s", String(style));
|
|
37
|
+
row.setAttribute("customFormat", "1");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
for (const { row, column, style } of layout.cells) {
|
|
41
|
+
let cells = changedCells.get(row);
|
|
42
|
+
if (!cells) {
|
|
43
|
+
cells = indexCells(rowAt(row));
|
|
44
|
+
changedCells.set(row, cells);
|
|
45
|
+
}
|
|
46
|
+
const cell = cells.get(column) ?? document.createElementNS(spreadNs, "c");
|
|
47
|
+
cell.setAttribute("r", formatWorkbookColumn(column) + (row + 1));
|
|
48
|
+
cell.setAttribute("s", String(style));
|
|
49
|
+
cells.set(column, cell);
|
|
50
|
+
}
|
|
51
|
+
for (const [row, cells] of changedCells) appendOrdered(rowAt(row), cells);
|
|
52
|
+
if (layout.rows?.length || layout.cells.length) appendOrdered(data, rows);
|
|
53
|
+
|
|
54
|
+
if (!layout.columns?.length) return;
|
|
55
|
+
const columns = child(worksheet, "cols") ?? document.createElementNS(spreadNs, "cols");
|
|
56
|
+
if (!columns.parentNode) worksheet.insertBefore(columns, data);
|
|
57
|
+
for (const { first, last, size, hidden, style } of layout.columns) {
|
|
58
|
+
const column = document.createElementNS(spreadNs, "col");
|
|
59
|
+
column.setAttribute("min", String(first + 1));
|
|
60
|
+
column.setAttribute("max", String(last + 1));
|
|
61
|
+
if (size !== undefined) {
|
|
62
|
+
column.setAttribute("width", String(size));
|
|
63
|
+
column.setAttribute("customWidth", "1");
|
|
64
|
+
}
|
|
65
|
+
if (hidden) column.setAttribute("hidden", "1");
|
|
66
|
+
if (style !== undefined) column.setAttribute("style", String(style));
|
|
67
|
+
columns.appendChild(column);
|
|
68
|
+
}
|
|
69
|
+
for (const column of children(columns, "col").sort((a, b) => readIndex(a, "min")! - readIndex(b, "min")!)) columns.appendChild(column);
|
|
70
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { SaxesParser } from "saxes";
|
|
2
|
+
import { isTrue, spreadNs } from "../../opc/xml";
|
|
3
|
+
|
|
4
|
+
const batchCharacters = 256 * 1024;
|
|
5
|
+
const maximumHeaderCharacters = 64 * 1024;
|
|
6
|
+
const wholeSheet = new Error("The worksheet needs its complete native data tree.");
|
|
7
|
+
|
|
8
|
+
/** @param xml - Checked original worksheet XML.
|
|
9
|
+
* @returns Native row batch boundaries, when no reader needs to revisit the entire sheetData tree. */
|
|
10
|
+
export function indexXlsxWorksheetRowBatches(xml: string) {
|
|
11
|
+
const parser = new SaxesParser({ xmlns: true });
|
|
12
|
+
let depth = 0;
|
|
13
|
+
let rootName = "", dataName = "";
|
|
14
|
+
let rootEnd = 0, dataOpen = 0, dataBegin = 0, dataEnd = 0;
|
|
15
|
+
let batchStart = 0, insideData = false;
|
|
16
|
+
const batchEnds: number[] = [];
|
|
17
|
+
|
|
18
|
+
// Source offsets come from the XML parser. Rebuilding both opening tags preserves the row namespace context.
|
|
19
|
+
parser.on("opentag", tag => {
|
|
20
|
+
depth++;
|
|
21
|
+
if (tag.local === "parsererror") throw wholeSheet;
|
|
22
|
+
if (depth === 1) {
|
|
23
|
+
if (tag.uri !== spreadNs || tag.local !== "worksheet") throw wholeSheet;
|
|
24
|
+
rootName = tag.name;
|
|
25
|
+
rootEnd = parser.position;
|
|
26
|
+
} else if (depth === 2) {
|
|
27
|
+
if (tag.local === "autoFilter" || tag.local === "tableParts"
|
|
28
|
+
|| tag.local === "sheetPr" && isTrue(tag.attributes.filterMode?.value)) throw wholeSheet;
|
|
29
|
+
if (tag.local !== "sheetData") return;
|
|
30
|
+
if (dataName || tag.uri !== spreadNs || tag.isSelfClosing) throw wholeSheet;
|
|
31
|
+
dataName = tag.name;
|
|
32
|
+
insideData = true;
|
|
33
|
+
dataBegin = batchStart = parser.position;
|
|
34
|
+
dataOpen = xml.lastIndexOf("<", dataBegin - 1);
|
|
35
|
+
if (dataOpen < rootEnd || rootEnd + dataBegin - dataOpen > maximumHeaderCharacters) throw wholeSheet;
|
|
36
|
+
} else if (insideData) {
|
|
37
|
+
// Outline and shared formula readers require sibling records that can cross a batch boundary.
|
|
38
|
+
if (depth === 3 && (tag.local !== "row" || tag.uri !== spreadNs || tag.attributes.outlineLevel
|
|
39
|
+
|| isTrue(tag.attributes.collapsed?.value))) throw wholeSheet;
|
|
40
|
+
if (depth === 5 && tag.local === "f" && tag.attributes.t?.value === "shared") throw wholeSheet;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
parser.on("closetag", () => {
|
|
44
|
+
if (insideData && depth === 3 && parser.position - batchStart >= batchCharacters) {
|
|
45
|
+
batchStart = parser.position;
|
|
46
|
+
batchEnds.push(batchStart);
|
|
47
|
+
} else if (insideData && depth === 2) {
|
|
48
|
+
insideData = false;
|
|
49
|
+
dataEnd = xml.lastIndexOf("<", parser.position - 1);
|
|
50
|
+
if (batchStart < dataEnd) batchEnds.push(dataEnd);
|
|
51
|
+
}
|
|
52
|
+
depth--;
|
|
53
|
+
});
|
|
54
|
+
try { parser.write(xml).close(); }
|
|
55
|
+
catch { return; }
|
|
56
|
+
if (batchEnds.length < 2) return;
|
|
57
|
+
return { dataBegin, dataEnd, batchEnds,
|
|
58
|
+
prefix: xml.slice(0, rootEnd) + xml.slice(dataOpen, dataBegin), suffix: `</${dataName}></${rootName}>` };
|
|
59
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { DOMParser, onErrorStopParsing } from "@xmldom/xmldom";
|
|
2
|
+
import { strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { afterEach, expect, it, vi } from "vitest";
|
|
4
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
5
|
+
import { spreadNs } from "../../opc/xml";
|
|
6
|
+
|
|
7
|
+
const worksheetPart = "xl/worksheets/sheet1.xml";
|
|
8
|
+
const rowFiller = "<!--" + "表🙂".repeat(50_000) + "-->\r\n";
|
|
9
|
+
|
|
10
|
+
/** @param body - Worksheet rows, including any special native values. @param tail - Worksheet metadata after the rows.
|
|
11
|
+
* @returns XLSX large enough to use the browser's bounded worksheet reader. */
|
|
12
|
+
function workbookFile(body: string, tail = ""): Uint8Array {
|
|
13
|
+
const seed = createXlsx({ version: 1, revision: 0, id: "test", name: "Book", sheets: [{ id: "sheet", name: "Test", cells: [] }] });
|
|
14
|
+
const parts = unzipSync(seed);
|
|
15
|
+
const paddingRows = `<s:row>${rowFiller}</s:row>`.repeat(16);
|
|
16
|
+
parts[worksheetPart] = strToU8(`<?xml version="1.0" encoding="UTF-8"?>\r\n<s:worksheet xmlns:s="${spreadNs}">
|
|
17
|
+
<s:sheetData xmlns:p="${spreadNs}">${body}${paddingRows}<p:row><p:c t="inlineStr"><p:is><p:t>末行 & 🙂</p:t></p:is></p:c></p:row>
|
|
18
|
+
</s:sheetData>${tail}</s:worksheet>`);
|
|
19
|
+
return zipSync(parts);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @returns A native-parser spy whose worksheets use the same XML nodes as the portable oracle. */
|
|
23
|
+
function watchNativeParser() {
|
|
24
|
+
const browser = new DOMParser({ onError: onErrorStopParsing });
|
|
25
|
+
const parse = vi.fn((xml: string, contentType: "application/xml") => browser.parseFromString(xml, contentType));
|
|
26
|
+
vi.stubGlobal("DOMParser", class { parseFromString = parse; });
|
|
27
|
+
return parse;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
afterEach(() => vi.unstubAllGlobals());
|
|
31
|
+
|
|
32
|
+
it("parses bounded worksheet batches in native order and writes from the original XML", () => {
|
|
33
|
+
const file = workbookFile(`<s:row r="4" ht="19.5" customHeight="1"><p:c r="B4" t="inlineStr"><p:is><p:t>字 < &</p:t></p:is></p:c>
|
|
34
|
+
<s:c><s:f>LEN(B4)</s:f><s:v>5</s:v></s:c></s:row><s:row hidden="1"><s:c><s:v>5.25</s:v></s:c></s:row>`,
|
|
35
|
+
'<s:mergeCells count="1"><s:mergeCell ref="A1:B1"/></s:mergeCells>');
|
|
36
|
+
const expected = openXlsx("Large", file);
|
|
37
|
+
const parse = watchNativeParser();
|
|
38
|
+
const result = openXlsx("Large", file);
|
|
39
|
+
const sheet = result.snapshot.sheets[0]!;
|
|
40
|
+
const originalSheet = expected.snapshot.sheets[0]!;
|
|
41
|
+
expect(parse.mock.calls.length).toBeGreaterThan(2);
|
|
42
|
+
expect(Math.max(...parse.mock.calls.map(([xml]) => xml.length))).toBeLessThan(600_000);
|
|
43
|
+
expect(sheet.cells).toEqual(originalSheet.cells);
|
|
44
|
+
expect(sheet.cells.at(-1)).toEqual({ row: 21, column: 0, input: { kind: "value", value: "末行 & 🙂" } });
|
|
45
|
+
expect(result.appearance.sheets.get(sheet.id)?.rows).toEqual(expected.appearance.sheets.get(originalSheet.id)?.rows);
|
|
46
|
+
expect(sheet.merges?.map(range => [range.startRow, range.endColumn])).toEqual([[0, 1]]);
|
|
47
|
+
expect(result.restrictions).toEqual(expected.restrictions);
|
|
48
|
+
expect(result.write(result.snapshot)).toEqual(file);
|
|
49
|
+
|
|
50
|
+
const cells = sheet.cells.map(cell => cell.row === 21 ? { ...cell, input: { kind: "value", value: "已更新" } as const } : cell);
|
|
51
|
+
const edited = result.write({ ...result.snapshot, sheets: [{ ...sheet, cells }] });
|
|
52
|
+
vi.unstubAllGlobals();
|
|
53
|
+
expect(openXlsx("Reopened", edited).snapshot.sheets[0]?.cells).toEqual(cells);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it.each([
|
|
57
|
+
["shared formulas", '<s:row r="1"><s:c r="B1"><s:f t="shared" si="1" ref="B1:B2">A1*2</s:f></s:c></s:row><s:row><s:c r="B2"><s:f t="shared" si="1"/></s:c></s:row>', ""],
|
|
58
|
+
["native row outlines", '<s:row r="1" outlineLevel="1"><s:c><s:v>1</s:v></s:c></s:row>', ""],
|
|
59
|
+
["native filters", '<s:row r="1"><s:c><s:v>1</s:v></s:c></s:row>', '<s:autoFilter ref="A1:A17"/>']
|
|
60
|
+
])("retains the whole worksheet reader for %s", (_name, rows, tail) => {
|
|
61
|
+
const file = workbookFile(rows, tail);
|
|
62
|
+
const expected = openXlsx("Large", file);
|
|
63
|
+
const parse = watchNativeParser();
|
|
64
|
+
const result = openXlsx("Large", file);
|
|
65
|
+
expect(parse).toHaveBeenCalledTimes(1);
|
|
66
|
+
expect(result.snapshot.sheets[0]?.cells).toEqual(expected.snapshot.sheets[0]?.cells);
|
|
67
|
+
expect(result.restrictions).toEqual(expected.restrictions);
|
|
68
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { child, children, parseWorksheetPart, parseXlsxWorksheetXml, readXlsxXmlPartText } from "../../opc/xml";
|
|
3
|
+
import { indexXlsxWorksheetRowBatches } from "./rows";
|
|
4
|
+
import type { XlsxWorksheetSource } from "./types";
|
|
5
|
+
|
|
6
|
+
const batchedWorksheetBytes = 4 * 1024 * 1024;
|
|
7
|
+
|
|
8
|
+
/** @param bytes - Original worksheet XML bytes. @param name - Part name for diagnostics.
|
|
9
|
+
* @param usesArrayMetadata - Whether the reader needs the whole sheet for derived array values.
|
|
10
|
+
* @returns Worksheet metadata and, for large independent row data, a bounded native row reader. */
|
|
11
|
+
export function openXlsxWorksheetSource(bytes: Uint8Array | undefined, name: string, usesArrayMetadata: boolean): XlsxWorksheetSource {
|
|
12
|
+
if (!bytes || bytes.length < batchedWorksheetBytes || usesArrayMetadata || typeof globalThis.DOMParser !== "function") {
|
|
13
|
+
return { root: parseWorksheetPart(bytes, name) };
|
|
14
|
+
}
|
|
15
|
+
const xml = readXlsxXmlPartText(bytes, name);
|
|
16
|
+
const sliced = indexXlsxWorksheetRowBatches(xml);
|
|
17
|
+
if (!sliced) return { root: parseXlsxWorksheetXml(xml, name) };
|
|
18
|
+
const { dataBegin, dataEnd, batchEnds, prefix, suffix } = sliced;
|
|
19
|
+
const root = parseXlsxWorksheetXml(xml.slice(0, dataBegin) + xml.slice(dataEnd), name);
|
|
20
|
+
|
|
21
|
+
/** @returns Rows in native order. Each batch's detached document can be collected before parsing later batches. */
|
|
22
|
+
function* readRows(): Iterable<Element> {
|
|
23
|
+
let start = dataBegin;
|
|
24
|
+
for (const end of batchEnds) {
|
|
25
|
+
const batch = parseXlsxWorksheetXml(prefix + xml.slice(start, end) + suffix, name);
|
|
26
|
+
yield* children(child(batch, "sheetData")!, "row");
|
|
27
|
+
start = end;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return { root, readRows };
|
|
31
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
|
|
3
|
+
/** Source XML for an import. Row batches replace the empty sheetData body's rows when available. */
|
|
4
|
+
export interface XlsxWorksheetSource {
|
|
5
|
+
/** Complete top-level worksheet metadata, including the original sheetData element. */
|
|
6
|
+
readonly root: Element;
|
|
7
|
+
/** Visits all native row elements in source order, with one batch of XML nodes live at a time. */
|
|
8
|
+
readonly readRows?: () => Iterable<Element>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
2
|
+
import { openWorkbook, parseWorkbookRange, workbookDateSerial, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
3
|
+
import { expect, it, vi } from "vitest";
|
|
4
|
+
import { createXlsx, openXlsx } from "../index";
|
|
5
|
+
|
|
6
|
+
const sheetPath = "xl/worksheets/sheet1.xml";
|
|
7
|
+
const seed: WorkbookSnapshot = { version: 1, revision: 0, id: "ledger", name: "Ledger", sheets: [
|
|
8
|
+
{ id: "orders", name: "Orders", cells: [
|
|
9
|
+
["Order", "Amount", "Region"], ["0007", 20, "South"], ["0008", 1, "East"], ["0009", 5, "East"], ["0010", 20, "North"], ["0011", 40, "South"]
|
|
10
|
+
].flatMap((values, row) => values.map((value, column) => ({ row, column, input: { kind: "value" as const, value } }))),
|
|
11
|
+
formats: [{ row: 1, column: 1, format: { background: "#DDEBDD" } }, { row: 1, column: 3, format: { bold: true } }] }
|
|
12
|
+
] };
|
|
13
|
+
|
|
14
|
+
/** @param autoFilter - Optional producer XML for the worksheet's filter. @returns Native OOXML fixture with row height and manual hiding. */
|
|
15
|
+
function nativeWorkbook(autoFilter = ""): Uint8Array {
|
|
16
|
+
const parts = unzipSync(createXlsx(seed));
|
|
17
|
+
parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!)
|
|
18
|
+
.replace('<row r="2">', '<row r="2" ht="34" customHeight="1">')
|
|
19
|
+
.replace('<row r="3">', '<row r="3" hidden="1">')
|
|
20
|
+
.replace("</worksheet>", autoFilter + "</worksheet>"));
|
|
21
|
+
return zipSync(parts);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
it("moves native styled cells, keeps row properties, and round-trips filter-specific hiding independently of manually hidden rows", async () => {
|
|
25
|
+
const file = openXlsx("Orders", nativeWorkbook());
|
|
26
|
+
const id = file.snapshot.sheets[0]!.id;
|
|
27
|
+
const target = parseWorkbookRange(id, "A1:D6");
|
|
28
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance, sortRestrictions: file.sortRestrictions });
|
|
29
|
+
try {
|
|
30
|
+
const edit = workbook.prepare({ operationId: "order-and-filter", baseRevision: 0, commands: [
|
|
31
|
+
{ name: "sortRows", target, params: { header: true, keys: [{ column: "B", direction: "asc" }] } },
|
|
32
|
+
{ name: "setWorksheetFilter", target, params: { columns: [{ column: "C", rule: { kind: "values", values: ["South"], blanks: false } }] } },
|
|
33
|
+
{ name: "setCells", target: parseWorkbookRange(id, "C2"), params: { cells: [[{ kind: "value", value: "South" }]] } }
|
|
34
|
+
] });
|
|
35
|
+
await workbook.commit(edit.id);
|
|
36
|
+
const exported = file.write(workbook.snapshot());
|
|
37
|
+
const data = unzipSync(exported);
|
|
38
|
+
const native = strFromU8(data[sheetPath]!);
|
|
39
|
+
expect(native).toContain('<autoFilter ref="A1:D6"><filterColumn colId="2"><filters><filter val="South"/>');
|
|
40
|
+
expect(native).toMatch(/<row r="2" ht="34" customHeight="1" hidden="1">/u);
|
|
41
|
+
expect(native).toContain('<qkf:visibility ref="A1:D6"');
|
|
42
|
+
expect(strFromU8(data["xl/workbook.xml"]!)).toContain("'Orders'!$A$1:$D$6");
|
|
43
|
+
|
|
44
|
+
const saved = openXlsx("Check", exported);
|
|
45
|
+
expect(saved.restrictions).toEqual([]);
|
|
46
|
+
expect(saved.snapshot.sheets[0]?.autoFilter?.hiddenRows).toEqual([1, 2, 4]);
|
|
47
|
+
const layout = saved.appearance.sheets.get(id)!;
|
|
48
|
+
expect(layout.rows.get(1)?.hidden).toBe(false);
|
|
49
|
+
expect(layout.rows.get(2)?.hidden).toBe(true);
|
|
50
|
+
expect(saved.appearance.styles[layout.cellStyles[3]![1]!]?.background).toBe("#DDEBDD");
|
|
51
|
+
expect(saved.appearance.styles[layout.cellStyles[3]![3]!]?.bold).toBe(true);
|
|
52
|
+
expect(saved.snapshot.sheets[0]?.cells.find(cell => cell.row === 1 && cell.column === 0)?.input).toMatchObject({ value: "0009" });
|
|
53
|
+
|
|
54
|
+
const reopened = await openWorkbook(saved.snapshot, { appearance: saved.appearance });
|
|
55
|
+
try {
|
|
56
|
+
const reset = reopened.prepare({ operationId: "clear", baseRevision: 0, commands: [{ name: "clearWorksheetFilter", target, params: {} }] });
|
|
57
|
+
await reopened.commit(reset.id);
|
|
58
|
+
const cleared = openXlsx("Cleared", saved.write(reopened.snapshot()));
|
|
59
|
+
expect(cleared.snapshot.sheets[0]?.autoFilter?.columns).toEqual([]);
|
|
60
|
+
expect([...cleared.appearance.sheets.get(id)!.rows].filter(([, properties]) => properties.hidden).map(([row]) => row)).toEqual([2]);
|
|
61
|
+
} finally { await reopened.close(); }
|
|
62
|
+
} finally { await workbook.close(); }
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("uses only native XLSX fields when row ownership can be recovered", async () => {
|
|
66
|
+
const file = openXlsx("Ordinary filter", nativeWorkbook());
|
|
67
|
+
const { snapshot, appearance } = file;
|
|
68
|
+
const id = snapshot.sheets[0]!.id;
|
|
69
|
+
const workbook = await openWorkbook(snapshot, { appearance });
|
|
70
|
+
try {
|
|
71
|
+
const target = parseWorkbookRange(id, "A1:C6");
|
|
72
|
+
const review = workbook.prepare({ operationId: "show-east", baseRevision: 0, commands: [{
|
|
73
|
+
name: "setWorksheetFilter", target, params: { columns: [{ column: "C", rule: { kind: "values", values: ["East"], blanks: false } }] }
|
|
74
|
+
}] });
|
|
75
|
+
await workbook.commit(review.id);
|
|
76
|
+
const bytes = file.write(workbook.snapshot());
|
|
77
|
+
expect(strFromU8(unzipSync(bytes)[sheetPath]!)).not.toContain("qkf:visibility");
|
|
78
|
+
|
|
79
|
+
const reloaded = openXlsx("Round trip", bytes);
|
|
80
|
+
expect(reloaded.restrictions).toEqual([]);
|
|
81
|
+
expect(reloaded.snapshot.sheets[0]?.autoFilter?.hiddenRows).toEqual([1, 4, 5]);
|
|
82
|
+
expect(reloaded.appearance.sheets.get(id)?.rows.get(2)?.hidden).toBe(true);
|
|
83
|
+
} finally { await workbook.close(); }
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("keeps patterned and white cells distinct from no fill when sorting imported records", async () => {
|
|
87
|
+
const sheet = seed.sheets[0]!;
|
|
88
|
+
const parts = unzipSync(createXlsx({ ...seed, sheets: [{ ...sheet, formats: [
|
|
89
|
+
...sheet.formats!, { row: 4, column: 1, format: { background: "#FFFFFF" } }
|
|
90
|
+
] }] }));
|
|
91
|
+
const stylePath = "xl/styles.xml";
|
|
92
|
+
const stylesheet = strFromU8(parts[stylePath]!);
|
|
93
|
+
const patterned = stylesheet.replace('<patternFill patternType="solid"><fgColor rgb="FFDDEBDD"',
|
|
94
|
+
'<patternFill patternType="lightGrid"><fgColor rgb="FFDDEBDD"');
|
|
95
|
+
expect(patterned).not.toBe(stylesheet);
|
|
96
|
+
parts[stylePath] = strToU8(patterned);
|
|
97
|
+
const source = openXlsx("Patterned fill", zipSync(parts));
|
|
98
|
+
const id = source.snapshot.sheets[0]!.id;
|
|
99
|
+
const workbook = await openWorkbook(source.snapshot, { appearance: source.appearance });
|
|
100
|
+
try {
|
|
101
|
+
expect(workbook.sortColorChoices(parseWorkbookRange(id, "B2:B6"), "fill")).toEqual([{ color: null, count: 3 }, { color: "#FFFFFF", count: 1 }]);
|
|
102
|
+
const target = parseWorkbookRange(id, "A1:B6");
|
|
103
|
+
const candidate = workbook.prepare({ operationId: "no-fill-first", baseRevision: 0, commands: [
|
|
104
|
+
{ name: "sortRows", target, params: { header: true, keys: [{ column: "B", source: "fill", color: null, position: "first" }] } }
|
|
105
|
+
] });
|
|
106
|
+
await workbook.commit(candidate.id);
|
|
107
|
+
const output = source.write(workbook.snapshot());
|
|
108
|
+
const reopened = openXlsx("Sorted", output);
|
|
109
|
+
expect(reopened.snapshot.sheets[0]?.cells.filter(cell => cell.column === 0).map(({ input }) => input)).toEqual(
|
|
110
|
+
["Order", "0008", "0009", "0011", "0007", "0010"].map(value => ({ kind: "value", value })));
|
|
111
|
+
expect(strFromU8(unzipSync(output)[stylePath]!)).toContain('<patternFill patternType="lightGrid">');
|
|
112
|
+
} finally { await workbook.close(); }
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("accepts native numeric comparisons and preserves unsupported producer filters unchanged", () => {
|
|
116
|
+
const understood = openXlsx("Known", nativeWorkbook('<autoFilter ref="A1:D6"><filterColumn colId="1">'
|
|
117
|
+
+ '<customFilters and="1"><customFilter operator="greaterThanOrEqual" val="5"/><customFilter operator="lessThan" val="30"/></customFilters>'
|
|
118
|
+
+ "</filterColumn></autoFilter>"));
|
|
119
|
+
expect(understood.restrictions).toEqual([]);
|
|
120
|
+
expect(understood.snapshot.sheets[0]?.autoFilter).toMatchObject({ hiddenRows: [2], columns: [
|
|
121
|
+
{ column: 1, rule: { kind: "custom", join: "all", conditions: [{ operator: "gte", value: "5" }, { operator: "lt", value: "30" }] } }
|
|
122
|
+
] });
|
|
123
|
+
|
|
124
|
+
const bytes = nativeWorkbook('<autoFilter ref="A1:D6"><filterColumn colId="1"><dynamicFilter type="aboveAverage" val="20"/></filterColumn></autoFilter>');
|
|
125
|
+
const unsupported = openXlsx("Unknown", bytes);
|
|
126
|
+
expect(unsupported.restrictions.join()).toMatch(/暂未支持的列条件/u);
|
|
127
|
+
expect(unsupported.write(unsupported.snapshot)).toEqual(bytes);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("round-trips a WPS following range and the earlier applied mask after an append", async () => {
|
|
131
|
+
const bytes = nativeWorkbook('<autoFilter ref="A1:C6" xmlns:etc="http://www.wps.cn/officeDocument/2017/etCustomData"'
|
|
132
|
+
+ ' etc:filterBottomFollowUsedRange="1"><filterColumn colId="2"><customFilters><customFilter val="South"/>'
|
|
133
|
+
+ '</customFilters></filterColumn><extLst/></autoFilter>');
|
|
134
|
+
const file = openXlsx("Following", bytes);
|
|
135
|
+
const sheet = file.snapshot.sheets[0]!;
|
|
136
|
+
expect(file.restrictions).toEqual([]);
|
|
137
|
+
expect(sheet.autoFilter).toMatchObject({ followUsedRows: true, hiddenRows: [2] });
|
|
138
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
139
|
+
const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
140
|
+
try {
|
|
141
|
+
const target = parseWorkbookRange(sheet.id, "C11");
|
|
142
|
+
await book.commit(book.prepare({ operationId: "extend-filter-range", baseRevision: 0,
|
|
143
|
+
commands: [{ name: "setCells", target, params: { value: "West" } }] }).id);
|
|
144
|
+
const output = file.write(book.snapshot());
|
|
145
|
+
const xml = strFromU8(unzipSync(output)[sheetPath]!);
|
|
146
|
+
expect(xml).toContain('<autoFilter ref="A1:C11"');
|
|
147
|
+
expect(xml).toContain('etc:filterBottomFollowUsedRange="1"');
|
|
148
|
+
expect(openXlsx("Reopened", output).snapshot.sheets[0]?.autoFilter).toEqual(book.autoFilter(sheet.id));
|
|
149
|
+
expect(book.filteredRows(sheet.id)).toEqual([2]);
|
|
150
|
+
await book.undo("revert-filter-range");
|
|
151
|
+
expect(file.write(book.snapshot())).toEqual(bytes);
|
|
152
|
+
} finally { await book.close(); }
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it("preserves original row flags when a relative date criterion has no saved bounds", () => {
|
|
156
|
+
const bytes = nativeWorkbook('<autoFilter ref="A1:D6"><filterColumn colId="1"><dynamicFilter type="lastMonth"/></filterColumn></autoFilter>');
|
|
157
|
+
const file = openXlsx("Undated row flags", bytes);
|
|
158
|
+
expect(file.restrictions.join()).toMatch(/缺少上次应用的区间/u);
|
|
159
|
+
expect(file.snapshot.sheets[0]?.autoFilter).toMatchObject({ hiddenRows: [],
|
|
160
|
+
columns: [{ column: 1, rule: { kind: "relativeDate", preset: "lastMonth" } }] });
|
|
161
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it.each(["serial", "iso"])("recovers the saved date window in %s form and writes recalculated native bounds", async (encoding) => {
|
|
165
|
+
const dateSystem: "1900" | "1904" = encoding === "serial" ? "1900" : "1904";
|
|
166
|
+
const sunday = workbookDateSerial(2026, 11, 29, dateSystem);
|
|
167
|
+
const rows = [["日期", "记录"], [sunday, "周日"], [sunday + 1.75, "午夜之前"], [sunday + 7, "下周"], [sunday + 2, "手工隐藏"]];
|
|
168
|
+
const workbook = { ...seed, dateSystem, sheets: [{
|
|
169
|
+
id: "orders", name: "Orders", cells: rows.flatMap((values, row) => values.map((value, column) => ({
|
|
170
|
+
row, column, input: { kind: "value" as const, value }
|
|
171
|
+
}))), formats: rows.slice(1).map((_, index) => ({ row: index + 1, column: 0, format: { numberFormat: "yyyy-mm-dd hh:mm" } }))
|
|
172
|
+
}] };
|
|
173
|
+
const parts = unzipSync(createXlsx(workbook));
|
|
174
|
+
const bounds = encoding === "serial" ? `val="${sunday}" maxVal="${sunday + 7}"`
|
|
175
|
+
: 'valIso="2026-11-29T00:00:00" maxValIso="2026-12-06T00:00:00Z"';
|
|
176
|
+
parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!)
|
|
177
|
+
.replace(/<row r="([45])">/gu, '<row r="$1" hidden="1">')
|
|
178
|
+
.replace("</worksheet>", `<autoFilter ref="A1:B5"><filterColumn colId="0"><dynamicFilter type="thisWeek" ${bounds}/></filterColumn><extLst/></autoFilter></worksheet>`));
|
|
179
|
+
const file = openXlsx("Relative dates", zipSync(parts));
|
|
180
|
+
const sheetId = file.snapshot.sheets[0]!.id;
|
|
181
|
+
const target = parseWorkbookRange(sheetId, "A1:B5");
|
|
182
|
+
const rule = { kind: "relativeDate", preset: "thisWeek" };
|
|
183
|
+
expect(file.restrictions).toEqual([]);
|
|
184
|
+
expect(file.snapshot.sheets[0]?.autoFilter).toMatchObject({
|
|
185
|
+
columns: [{ rule, dateWindow: { start: sunday, end: sunday + 7 } }], hiddenRows: [3]
|
|
186
|
+
});
|
|
187
|
+
expect(file.appearance.sheets.get(sheetId)?.rows.get(4)?.hidden).toBe(true);
|
|
188
|
+
const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
189
|
+
vi.useFakeTimers({ toFake: ["Date"] });
|
|
190
|
+
try {
|
|
191
|
+
vi.setSystemTime(new Date(2026, 11, 7, 12));
|
|
192
|
+
expect(book.autoFilter(sheetId)?.hiddenRows).toEqual([3]);
|
|
193
|
+
const draft = book.prepare({ operationId: "reapply-next-week", baseRevision: 0,
|
|
194
|
+
commands: [{ name: "reapplyWorksheetFilter", target, params: {} }] });
|
|
195
|
+
await book.commit(draft.id);
|
|
196
|
+
expect(book.autoFilter(sheetId)).toMatchObject({ hiddenRows: [1, 2, 4],
|
|
197
|
+
columns: [{ rule, dateWindow: { start: sunday + 7, end: sunday + 14 } }] });
|
|
198
|
+
const output = file.write(book.snapshot());
|
|
199
|
+
const xml = strFromU8(unzipSync(output)[sheetPath]!);
|
|
200
|
+
expect(xml).toContain(`<dynamicFilter type="thisWeek" val="${sunday + 7}" maxVal="${sunday + 14}"/>`);
|
|
201
|
+
const saved = openXlsx("Reapplied", output);
|
|
202
|
+
expect(saved.snapshot.sheets[0]?.autoFilter).toEqual(book.autoFilter(sheetId));
|
|
203
|
+
expect(saved.appearance.sheets.get(sheetId)?.rows.get(4)?.hidden).toBe(true);
|
|
204
|
+
} finally { vi.useRealTimers(); await book.close(); }
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it("reads and writes native calendar groups, numerical cutoffs and manual row ownership", async () => {
|
|
208
|
+
const january = workbookDateSerial(2026, 1, 15, "1904");
|
|
209
|
+
const initial = { ...seed, dateSystem: "1904" as const, sheets: [{ id: "orders", name: "订单", cells: [
|
|
210
|
+
["日期", "金额"], [january + 0.5, 80], [january, 80], [january + 31, 900], ["待定", 80], ["", 10], [january, 100]
|
|
211
|
+
].flatMap((values, row) => values.map((value, column) => ({ row, column, input: { kind: "value" as const, value } }))),
|
|
212
|
+
formats: [1, 3, 6].map(row => ({ row, column: 0, format: { numberFormat: 'yyyy"年"m"月"d"日" h:mm' } })) }] };
|
|
213
|
+
const parts = unzipSync(createXlsx(initial));
|
|
214
|
+
parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!)
|
|
215
|
+
.replace(/<row r="([3467])">/gu, '<row r="$1" hidden="1">')
|
|
216
|
+
.replace("</worksheet>", '<autoFilter ref="A1:B7"><filterColumn colId="0"><filters blank="1" calendarType="gregorian">'
|
|
217
|
+
+ '<filter val="待定"/><dateGroupItem year="2026" month="1" dateTimeGrouping="month"/></filters></filterColumn>'
|
|
218
|
+
+ '<filterColumn colId="1"><top10 val="3"/></filterColumn></autoFilter></worksheet>'));
|
|
219
|
+
const source = openXlsx("Calendar and rank", zipSync(parts));
|
|
220
|
+
const id = source.snapshot.sheets[0]!.id;
|
|
221
|
+
expect(source.restrictions).toEqual([]);
|
|
222
|
+
expect(source.snapshot.sheets[0]?.autoFilter).toMatchObject({
|
|
223
|
+
hiddenRows: [2, 3, 5], columns: [
|
|
224
|
+
{ column: 0, rule: { kind: "values", values: ["待定"], blanks: true, dates: ["2026-01"] } },
|
|
225
|
+
{ column: 1, rule: { kind: "rank", order: "top", unit: "items", count: 3 }, cutoff: 80 }
|
|
226
|
+
]
|
|
227
|
+
});
|
|
228
|
+
expect(source.appearance.sheets.get(id)?.rows.get(6)?.hidden).toBe(true);
|
|
229
|
+
const workbook = await openWorkbook(source.snapshot, { appearance: source.appearance });
|
|
230
|
+
try {
|
|
231
|
+
const target = parseWorkbookRange(id, "A1:B7");
|
|
232
|
+
const preview = workbook.prepare({ operationId: "smallest-with-date", baseRevision: workbook.revision, commands: [
|
|
233
|
+
{ name: "setWorksheetFilter", target, params: { columns: [
|
|
234
|
+
{ column: "A", rule: { kind: "values", values: ["待定"], blanks: true, dates: ["2026-01-15"] } },
|
|
235
|
+
{ column: "B", rule: { kind: "rank", order: "bottom", unit: "percent", count: 25 } }
|
|
236
|
+
] } }
|
|
237
|
+
] });
|
|
238
|
+
await workbook.commit(preview.id);
|
|
239
|
+
const exported = source.write(workbook.snapshot());
|
|
240
|
+
const native = strFromU8(unzipSync(exported)[sheetPath]!);
|
|
241
|
+
expect(native).toContain('<dateGroupItem year="2026" dateTimeGrouping="day" month="1" day="15"/>');
|
|
242
|
+
expect(native).toContain('<top10 top="0" percent="1" val="25" filterVal="80"/>');
|
|
243
|
+
const saved = openXlsx("Saved criteria", exported);
|
|
244
|
+
expect(saved.restrictions).toEqual([]);
|
|
245
|
+
expect(saved.snapshot.sheets[0]?.autoFilter).toEqual(workbook.autoFilter(id));
|
|
246
|
+
expect(saved.snapshot.sheets[0]?.autoFilter?.hiddenRows).toEqual([2, 3, 6]);
|
|
247
|
+
expect(saved.appearance.sheets.get(id)?.rows.get(6)?.hidden).toBe(true);
|
|
248
|
+
} finally { await workbook.close(); }
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it("restores color criteria from native differential styles and retains manual row ownership", async () => {
|
|
252
|
+
const parts = unzipSync(createXlsx(seed));
|
|
253
|
+
const stylesPath = "xl/styles.xml";
|
|
254
|
+
parts[stylesPath] = strToU8(strFromU8(parts[stylesPath]!).replace("</styleSheet>",
|
|
255
|
+
'<dxfs count="1"><dxf><fill><patternFill patternType="solid"><fgColor rgb="FFDDEBDD"/></patternFill></fill></dxf></dxfs></styleSheet>'));
|
|
256
|
+
parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!)
|
|
257
|
+
.replace(/<row r="([2356])">/gu, '<row r="$1" hidden="1">')
|
|
258
|
+
.replace("</worksheet>", '<autoFilter ref="A1:C6"><filterColumn colId="1"><colorFilter dxfId="0"/></filterColumn></autoFilter></worksheet>'));
|
|
259
|
+
const source = openXlsx("Color fixture", zipSync(parts));
|
|
260
|
+
const id = source.snapshot.sheets[0]!.id;
|
|
261
|
+
const range = parseWorkbookRange(id, "A1:C6");
|
|
262
|
+
const column = { column: 1, rule: { kind: "color", source: "fill", color: "#DDEBDD" } };
|
|
263
|
+
expect(source.restrictions).toEqual([]);
|
|
264
|
+
expect(source.snapshot.sheets[0]?.autoFilter).toEqual({ range, columns: [column], hiddenRows: [2, 4, 5] });
|
|
265
|
+
expect(source.appearance.sheets.get(id)?.rows.get(1)?.hidden).toBe(true);
|
|
266
|
+
|
|
267
|
+
const workbook = await openWorkbook(source.snapshot, { appearance: source.appearance });
|
|
268
|
+
try {
|
|
269
|
+
const match = parseWorkbookRange(id, "B3");
|
|
270
|
+
const painted = workbook.prepare({ baseRevision: 0, operationId: "recolor", commands: [{
|
|
271
|
+
name: "setCellFormat", target: match, params: { background: "#DDEBDD" }
|
|
272
|
+
}] });
|
|
273
|
+
await workbook.commit(painted.id);
|
|
274
|
+
const saved = openXlsx("Color result", source.write(workbook.snapshot()));
|
|
275
|
+
expect(saved.restrictions).toEqual([]);
|
|
276
|
+
expect(saved.snapshot.sheets[0]?.autoFilter).toEqual({ range, columns: [column], hiddenRows: [2, 4, 5] });
|
|
277
|
+
expect(saved.appearance.sheets.get(id)?.rows.get(1)?.hidden).toBe(true);
|
|
278
|
+
|
|
279
|
+
const filter = workbook.prepare({ baseRevision: workbook.revision, operationId: "new-colors", commands: [{
|
|
280
|
+
name: "reapplyWorksheetFilter", target: range, params: {}
|
|
281
|
+
}] });
|
|
282
|
+
await workbook.commit(filter.id);
|
|
283
|
+
expect(workbook.autoFilter(id)?.hiddenRows).toEqual([3, 4, 5]);
|
|
284
|
+
const reapplied = openXlsx("Reapplied colors", source.write(workbook.snapshot()));
|
|
285
|
+
expect(reapplied.snapshot.sheets[0]?.autoFilter).toEqual(workbook.autoFilter(id));
|
|
286
|
+
expect(reapplied.appearance.sheets.get(id)?.rows.get(1)?.hidden).toBe(true);
|
|
287
|
+
} finally { await workbook.close(); }
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it("reads WPS font color criteria and preserves ambiguous native conditional row flags", async () => {
|
|
291
|
+
const parts = unzipSync(createXlsx(seed));
|
|
292
|
+
const stylesPath = "xl/styles.xml";
|
|
293
|
+
parts[stylesPath] = strToU8(strFromU8(parts[stylesPath]!).replace("</styleSheet>",
|
|
294
|
+
'<dxfs count="2"><dxf><fill><patternFill patternType="solid"><fgColor rgb="FFD73434"/><bgColor rgb="FFFFFFFF"/></patternFill></fill></dxf>'
|
|
295
|
+
+ '<dxf><font><color rgb="FFD73434"/></font></dxf></dxfs></styleSheet>'));
|
|
296
|
+
parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!)
|
|
297
|
+
.replace(/<row r="([345])">/gu, '<row r="$1" hidden="1">')
|
|
298
|
+
.replace("</worksheet>", '<autoFilter ref="A1:C6" xmlns:et="http://www.wps.cn/officeDocument/2017/etCustomData" et:filterBottomFollowUsedRange="0">'
|
|
299
|
+
+ '<filterColumn colId="1"><colorFilter dxfId="0" cellColor="0"/></filterColumn><extLst/></autoFilter>'
|
|
300
|
+
+ '<conditionalFormatting sqref="B2:B6"><cfRule type="cellIs" dxfId="1" priority="1" operator="greaterThan"><formula>30</formula></cfRule></conditionalFormatting></worksheet>'));
|
|
301
|
+
const bytes = zipSync(parts);
|
|
302
|
+
const file = openXlsx("WPS conditional color", bytes);
|
|
303
|
+
const { id, autoFilter } = file.snapshot.sheets[0]!;
|
|
304
|
+
expect(autoFilter?.columns).toEqual([{ column: 1, rule: { kind: "color", source: "font", color: "#D73434" } }]);
|
|
305
|
+
expect(file.restrictions).toEqual(["条件格式着色筛选需要原件保全"]);
|
|
306
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
307
|
+
const book = await openWorkbook(file.snapshot, { appearance: file.appearance, isEditable: () => false });
|
|
308
|
+
try {
|
|
309
|
+
expect(book.readDataColor({ sheetId: id, row: 5, column: 1 }, "font")).toBe("#D73434");
|
|
310
|
+
expect(book.readDataColor({ sheetId: id, row: 1, column: 1 }, "font")).toBe("#000000");
|
|
311
|
+
expect([2, 3, 4].every(row => book.isCellHidden({ sheetId: id, row, column: 1 }))).toBe(true);
|
|
312
|
+
expect(book.isCellHidden({ sheetId: id, row: 1, column: 1 })).toBe(false);
|
|
313
|
+
} finally { await book.close(); }
|
|
314
|
+
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { workbookColumns } from "@quirekit/workbook";
|
|
3
|
+
import type { XlsxColumnLayoutSpan } from "../outline/types";
|
|
4
|
+
import { child, children, readIndex, spreadNs } from "../../opc/xml";
|
|
5
|
+
|
|
6
|
+
/** @param spans - Sorted authored intervals. @param first - First candidate column.
|
|
7
|
+
* @returns Index of the first interval whose end reaches the current source record. */
|
|
8
|
+
function findOverlap(spans: readonly XlsxColumnLayoutSpan[], first: number): number {
|
|
9
|
+
let low = 0, high = spans.length;
|
|
10
|
+
while (low < high) {
|
|
11
|
+
const middle = (low + high) >>> 1;
|
|
12
|
+
if (spans[middle]!.last < first) low = middle + 1;
|
|
13
|
+
else high = middle;
|
|
14
|
+
}
|
|
15
|
+
return low;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param record - Native column record. @param first - First column. @param last - Last column.
|
|
19
|
+
* @param patch - Authored dimensions for this particular part of the original range.
|
|
20
|
+
* @returns Detached record preserving all other attributes. */
|
|
21
|
+
function writeSegment(record: Element, first: number, last: number, patch?: XlsxColumnLayoutSpan): Element {
|
|
22
|
+
const next = record.cloneNode(true) as Element;
|
|
23
|
+
next.setAttribute("min", String(first + 1));
|
|
24
|
+
next.setAttribute("max", String(last + 1));
|
|
25
|
+
if (patch?.size !== undefined) {
|
|
26
|
+
next.setAttribute("width", String(patch.size));
|
|
27
|
+
next.setAttribute("customWidth", "1");
|
|
28
|
+
next.removeAttribute("bestFit");
|
|
29
|
+
}
|
|
30
|
+
if (patch?.hidden === true) next.setAttribute("hidden", "1");
|
|
31
|
+
else if (patch?.hidden === false) next.removeAttribute("hidden");
|
|
32
|
+
if (patch?.outlineLevel !== undefined) {
|
|
33
|
+
if (patch.outlineLevel) next.setAttribute("outlineLevel", String(patch.outlineLevel));
|
|
34
|
+
else next.removeAttribute("outlineLevel");
|
|
35
|
+
}
|
|
36
|
+
if (patch?.collapsed === true) next.setAttribute("collapsed", "1");
|
|
37
|
+
else if (patch?.collapsed === false) next.removeAttribute("collapsed");
|
|
38
|
+
return next;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param root - Worksheet after its positional edits. @param spans - Authored column overrides at the final coordinates. */
|
|
42
|
+
export function writeXlsxColumnDimensions(root: Element, spans: readonly XlsxColumnLayoutSpan[]): void {
|
|
43
|
+
if (!spans.length) return;
|
|
44
|
+
const doc = root.ownerDocument!;
|
|
45
|
+
const original = child(root, "cols");
|
|
46
|
+
const cols = original ?? doc.createElementNS(spreadNs, "cols");
|
|
47
|
+
if (!original) root.insertBefore(cols, child(root, "sheetData") ?? null);
|
|
48
|
+
const covered = new Uint8Array(workbookColumns);
|
|
49
|
+
|
|
50
|
+
// Split the records that overlap an edit, cloning the source's style, outline, and other retained attributes.
|
|
51
|
+
for (const record of children(cols, "col")) {
|
|
52
|
+
const min = readIndex(record, "min"), max = readIndex(record, "max");
|
|
53
|
+
if (!min || !max || max < min || max > workbookColumns) continue;
|
|
54
|
+
const first = min - 1, last = max - 1;
|
|
55
|
+
covered.fill(1, first, last + 1);
|
|
56
|
+
const index = findOverlap(spans, first);
|
|
57
|
+
if (!spans[index] || spans[index]!.first > last) continue;
|
|
58
|
+
let cursor = first;
|
|
59
|
+
for (let i = index; i < spans.length && spans[i]!.first <= last; i++) {
|
|
60
|
+
const span = spans[i]!;
|
|
61
|
+
const start = Math.max(cursor, span.first), end = Math.min(last, span.last);
|
|
62
|
+
if (cursor < start) cols.insertBefore(writeSegment(record, cursor, start - 1), record);
|
|
63
|
+
cols.insertBefore(writeSegment(record, start, end, span), record);
|
|
64
|
+
cursor = end + 1;
|
|
65
|
+
}
|
|
66
|
+
if (cursor <= last) cols.insertBefore(writeSegment(record, cursor, last), record);
|
|
67
|
+
cols.removeChild(record);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Fill uncovered coordinates in order without disturbing any overlapping records the producer retained.
|
|
71
|
+
const ordered = children(cols, "col");
|
|
72
|
+
const blank = doc.createElementNS(spreadNs, "col");
|
|
73
|
+
let insertion = 0;
|
|
74
|
+
for (const span of spans) {
|
|
75
|
+
if (span.size === undefined && !span.hidden && !span.outlineLevel && !span.collapsed) continue;
|
|
76
|
+
let first = span.first;
|
|
77
|
+
while (first <= span.last) {
|
|
78
|
+
if (covered[first]) { first++; continue; }
|
|
79
|
+
let last = first;
|
|
80
|
+
while (last < span.last && !covered[last + 1]) last++;
|
|
81
|
+
while (insertion < ordered.length && (readIndex(ordered[insertion], "min") ?? 0) <= first + 1) insertion++;
|
|
82
|
+
cols.insertBefore(writeSegment(blank, first, last, span), ordered[insertion] ?? null);
|
|
83
|
+
first = last + 1;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (!children(cols, "col").length) root.removeChild(cols);
|
|
87
|
+
}
|