@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,217 @@
|
|
|
1
|
+
import { workbookLiteralResult,
|
|
2
|
+
copyWorkbookChart, maximumWorkbookCharts, readWorkbookChartData, sameWorkbookChart, sameWorkbookFloatingPicture, workbookChartDataRanges, workbookColumns,
|
|
3
|
+
type WorkbookAddress, type WorkbookCell, type WorkbookChart, type WorkbookRasterMimeType, type WorkbookSnapshot
|
|
4
|
+
} from "@quirekit/workbook";
|
|
5
|
+
import { editPartRelationships, hyperlinkRelationship, relationshipsPath } from "../../opc/relationships";
|
|
6
|
+
import { children, contentTypeNs, parsePart, relationshipNs, rootOf, spreadNs, writePart } from "../../opc/xml";
|
|
7
|
+
import type { XlsxPackage } from "../../package/types";
|
|
8
|
+
import type { XlsxWriteOptions } from "../../types";
|
|
9
|
+
import { drawingContentTypes } from "../namespaces";
|
|
10
|
+
import { readXlsxDrawingLayout } from "../placement/axes";
|
|
11
|
+
import type { XlsxChartPart, XlsxDrawingFrame } from "../types";
|
|
12
|
+
import { writeChartSpace } from "./chart";
|
|
13
|
+
import { writeXlsxDrawing, writeXlsxDrawingRelationships, writeWorksheetDrawing } from "./drawing";
|
|
14
|
+
import { planXlsxPictures } from "./pictures";
|
|
15
|
+
import { planXlsxShapes, sameXlsxShape } from "./shapes";
|
|
16
|
+
|
|
17
|
+
/** @param snapshot - Saved data. @param options - Cache access for the same revision.
|
|
18
|
+
* @returns Sparse lookup scoped to the sheets referenced by charts. */
|
|
19
|
+
function snapshotPointReader(snapshot: WorkbookSnapshot, options: XlsxWriteOptions) {
|
|
20
|
+
const sheets = new Map(snapshot.sheets.map(sheet => [sheet.id, sheet.cells]));
|
|
21
|
+
const rows = new Map<string, Map<number, WorkbookCell>>();
|
|
22
|
+
return {
|
|
23
|
+
/** @param address - Source cell. @returns Stored input or formula value. */
|
|
24
|
+
read(address: WorkbookAddress) {
|
|
25
|
+
const { sheetId, row, column } = address;
|
|
26
|
+
let inputs = rows.get(sheetId);
|
|
27
|
+
if (!inputs) {
|
|
28
|
+
inputs = new Map(sheets.get(sheetId)?.map(({ row, column, input }) => [row * workbookColumns + column, input]));
|
|
29
|
+
rows.set(sheetId, inputs);
|
|
30
|
+
}
|
|
31
|
+
const input = inputs.get(row * workbookColumns + column);
|
|
32
|
+
return { result: input?.kind === "formula" ? options.result?.(address) ?? { status: "unavailable" as const }
|
|
33
|
+
: workbookLiteralResult(input ?? null), formula: input?.kind === "formula" };
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @param left - Earlier checkpoint. @param right - New checkpoint. @returns Whether ordered chart definitions are equal. */
|
|
39
|
+
export function sameXlsxCharts(left: WorkbookSnapshot, right: WorkbookSnapshot): boolean {
|
|
40
|
+
const before = left.charts ?? [], after = right.charts ?? [];
|
|
41
|
+
return before.length === after.length && before.every((chart, index) => sameWorkbookChart(chart, after[index]!));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Writes exclusively owned drawings. Existing identities survive source edits
|
|
46
|
+
* and new parts reserve paths against every original member before allocation.
|
|
47
|
+
* @param source - Package and validated original drawing graphs.
|
|
48
|
+
* @param parts - Staged archive entries.
|
|
49
|
+
* @param paths - Final worksheet part paths by ID.
|
|
50
|
+
* @param snapshot - Committed chart definitions and their data.
|
|
51
|
+
* @param options - Calculated values for the saved revision.
|
|
52
|
+
* @param refreshData - Inputs or workbook references may have changed.
|
|
53
|
+
* @param revisedLayout - Worksheets whose saved row or column geometry changed.
|
|
54
|
+
*/
|
|
55
|
+
export function writeWorkbookDrawings(source: XlsxPackage, parts: Record<string, Uint8Array>, paths: ReadonlyMap<string, string>,
|
|
56
|
+
snapshot: WorkbookSnapshot, options: XlsxWriteOptions, refreshData: boolean, revisedLayout: ReadonlySet<string>): void {
|
|
57
|
+
if (!snapshot.charts?.length && !snapshot.pictures?.length && !snapshot.shapes?.length && !source.drawingGraphs?.size) return;
|
|
58
|
+
const images = planXlsxPictures(source, parts, paths, snapshot);
|
|
59
|
+
const shapes = planXlsxShapes(snapshot, paths);
|
|
60
|
+
const names = new Map(snapshot.sheets.map(sheet => [sheet.id, sheet.name]));
|
|
61
|
+
const bySheet = new Map<string, WorkbookChart[]>();
|
|
62
|
+
const chartIds = new Set<string>();
|
|
63
|
+
if ((snapshot.charts?.length ?? 0) > maximumWorkbookCharts) throw new Error("工作簿的可编辑图表数量过多。");
|
|
64
|
+
for (const item of snapshot.charts ?? []) {
|
|
65
|
+
const chart = copyWorkbookChart(item);
|
|
66
|
+
const id = chart.anchor.sheetId;
|
|
67
|
+
if (chartIds.has(chart.id) || !paths.has(id) || workbookChartDataRanges(chart).some(range => !names.has(range.sheetId))) {
|
|
68
|
+
throw new Error("图表标识重复或引用了不存在的工作表。");
|
|
69
|
+
}
|
|
70
|
+
const owned = bySheet.get(id) ?? [];
|
|
71
|
+
owned.push(chart);
|
|
72
|
+
bySheet.set(id, owned);
|
|
73
|
+
chartIds.add(chart.id);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const manifestPath = "[Content_Types].xml";
|
|
77
|
+
const manifest = parsePart(parts[manifestPath], manifestPath), root = rootOf(manifest, contentTypeNs, "Types");
|
|
78
|
+
const overrides = new Map(children(root, "Override").map(item => [item.getAttribute("PartName"), item]));
|
|
79
|
+
const reserved = new Set(Object.keys(parts).map(path => path.toLowerCase()));
|
|
80
|
+
const base = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
|
|
81
|
+
const serial = { chart: 1, drawing: 1, picture: 1 };
|
|
82
|
+
let manifestChanged = false;
|
|
83
|
+
const reader = snapshotPointReader(snapshot, options);
|
|
84
|
+
|
|
85
|
+
/** @param kind - Content type of a new owned part. @returns Unused part URI from the workbook's directory. */
|
|
86
|
+
function allocate(kind: "chart" | "drawing"): string {
|
|
87
|
+
let path: string;
|
|
88
|
+
do { path = `${base}${kind}s/${kind}${serial[kind]++}.xml`; }
|
|
89
|
+
while (reserved.has(path.toLowerCase()) || reserved.has(relationshipsPath(path).toLowerCase()));
|
|
90
|
+
return declare(path, drawingContentTypes[kind]);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** @param mime - Referenced raster format. @returns New media path protected from collisions. */
|
|
94
|
+
function allocateMedia(mime: WorkbookRasterMimeType): string {
|
|
95
|
+
const extension = mime === "image/png" ? "png" : "jpeg";
|
|
96
|
+
let path: string;
|
|
97
|
+
do { path = `${base}media/picture${serial.picture++}.${extension}`; }
|
|
98
|
+
while (reserved.has(path.toLowerCase()) || reserved.has(relationshipsPath(path).toLowerCase()));
|
|
99
|
+
return declare(path, mime);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @param path - New package path. @param type - Its OPC content type. @returns The reserved path. */
|
|
103
|
+
function declare(path: string, type: string): string {
|
|
104
|
+
reserved.add(path.toLowerCase());
|
|
105
|
+
const override = manifest.createElementNS(contentTypeNs, "Override");
|
|
106
|
+
override.setAttribute("PartName", "/" + path);
|
|
107
|
+
override.setAttribute("ContentType", type);
|
|
108
|
+
root.appendChild(override);
|
|
109
|
+
manifestChanged = true;
|
|
110
|
+
return path;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** @param path - Exclusively owned native part that no longer has a reference. */
|
|
114
|
+
function remove(path: string): void {
|
|
115
|
+
delete parts[path];
|
|
116
|
+
delete parts[relationshipsPath(path)];
|
|
117
|
+
const override = overrides.get("/" + path);
|
|
118
|
+
if (override) { root.removeChild(override); manifestChanged = true; }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
for (const sheetId of new Set([...(source.drawingGraphs?.keys() ?? []), ...bySheet.keys(), ...images.bySheet.keys(), ...shapes.keys()])) {
|
|
122
|
+
const native = source.drawingGraphs?.get(sheetId);
|
|
123
|
+
const path = paths.get(sheetId);
|
|
124
|
+
const charts = bySheet.get(sheetId) ?? [];
|
|
125
|
+
const pictures = images.bySheet.get(sheetId) ?? [];
|
|
126
|
+
const worksheetShapes = shapes.get(sheetId) ?? [];
|
|
127
|
+
const before = new Map(native?.parts.map(part => [part.chart.id, part]));
|
|
128
|
+
if (!path || !charts.length && !pictures.length && !worksheetShapes.length) {
|
|
129
|
+
if (native) {
|
|
130
|
+
for (const { path } of native.parts) remove(path);
|
|
131
|
+
remove(native.drawingPath);
|
|
132
|
+
if (path) {
|
|
133
|
+
const relationships = editPartRelationships(parts, path);
|
|
134
|
+
relationships.remove(native.relationshipId);
|
|
135
|
+
relationships.write();
|
|
136
|
+
writeWorksheetDrawing(parts, path, undefined);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const after: XlsxChartPart[] = [];
|
|
142
|
+
const frames = [...(native?.parts ?? []), ...(native?.pictures ?? [])];
|
|
143
|
+
const originalShapes = native?.shapes ?? [];
|
|
144
|
+
const occupied = new Set([...frames, ...originalShapes].map(part => part.frameId));
|
|
145
|
+
const linked = new Set(frames.map(part => part.relationshipId));
|
|
146
|
+
let nextFrame = 1, nextRelationship = 1;
|
|
147
|
+
/** @returns The next unused object ID in this drawing. */
|
|
148
|
+
function frameId(): number {
|
|
149
|
+
while (occupied.has(nextFrame)) nextFrame++;
|
|
150
|
+
return nextFrame++;
|
|
151
|
+
}
|
|
152
|
+
/** @returns A new drawing-local OPC relationship ID. */
|
|
153
|
+
function relationshipId(): string {
|
|
154
|
+
while (linked.has(`rId${nextRelationship}`)) nextRelationship++;
|
|
155
|
+
return `rId${nextRelationship++}`;
|
|
156
|
+
}
|
|
157
|
+
for (const chart of charts) {
|
|
158
|
+
const prior = before.get(chart.id);
|
|
159
|
+
if (prior) {
|
|
160
|
+
after.push({ ...prior, chart });
|
|
161
|
+
before.delete(chart.id);
|
|
162
|
+
if (refreshData || !sameWorkbookChart(prior.chart, chart)) {
|
|
163
|
+
parts[prior.path] = writeChartSpace(chart, readWorkbookChartData(chart, reader), names);
|
|
164
|
+
}
|
|
165
|
+
} else {
|
|
166
|
+
const objectId = frameId();
|
|
167
|
+
const part = { chart, path: allocate("chart"), frameId: objectId, frameName: `Chart ${objectId}`, relationshipId: relationshipId() };
|
|
168
|
+
after.push(part);
|
|
169
|
+
parts[part.path] = writeChartSpace(chart, readWorkbookChartData(chart, reader), names);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
for (const { path } of before.values()) remove(path);
|
|
173
|
+
const drawingPath = native?.drawingPath ?? allocate("drawing");
|
|
174
|
+
const originalParts = native?.parts ?? [];
|
|
175
|
+
const originalPictures = native?.pictures ?? [];
|
|
176
|
+
const priorPictures = new Map(originalPictures.map(part => [part.picture.id, part]));
|
|
177
|
+
const nextPictures = pictures.map(picture => {
|
|
178
|
+
const prior = priorPictures.get(picture.id);
|
|
179
|
+
const media = images.path(picture.assetId, allocateMedia);
|
|
180
|
+
return { picture, path: media, frameId: prior?.frameId ?? frameId(),
|
|
181
|
+
relationshipId: prior?.path === media ? prior.relationshipId : relationshipId() };
|
|
182
|
+
});
|
|
183
|
+
const priorShapes = new Map(originalShapes.map(part => [part.shape.id, part]));
|
|
184
|
+
const nextShapes = worksheetShapes.map(shape => ({ shape, frameId: priorShapes.get(shape.id)?.frameId ?? frameId() }));
|
|
185
|
+
const needsDrawingLayout = pictures.some(picture => picture.rotation)
|
|
186
|
+
|| worksheetShapes.some(shape => shape.rotation || shape.connector);
|
|
187
|
+
const changed = needsDrawingLayout && revisedLayout.has(sheetId) || after.length !== originalParts.length || after.some(({ chart }, index) => {
|
|
188
|
+
const original = originalParts[index]?.chart;
|
|
189
|
+
return original?.id !== chart.id || original.order !== chart.order || JSON.stringify(original.anchor) !== JSON.stringify(chart.anchor);
|
|
190
|
+
}) || nextPictures.length !== originalPictures.length || nextPictures.some(({ picture, path }) => {
|
|
191
|
+
const prior = priorPictures.get(picture.id);
|
|
192
|
+
return path !== prior?.path || !sameWorkbookFloatingPicture(prior.picture, picture);
|
|
193
|
+
}) || nextShapes.length !== originalShapes.length || nextShapes.some(({ shape }) => !sameXlsxShape(priorShapes.get(shape.id)?.shape, shape));
|
|
194
|
+
if (changed) {
|
|
195
|
+
const ordered: { readonly part: XlsxDrawingFrame; readonly order: number }[] = after.map((part, index) => ({ part, order: part.chart.order ?? index }));
|
|
196
|
+
for (const part of nextPictures) ordered.push({ part, order: part.picture.order });
|
|
197
|
+
for (const part of nextShapes) ordered.push({ part, order: part.shape.order });
|
|
198
|
+
const frames = ordered.sort((left, right) => left.order - right.order).map(({ part }) => part);
|
|
199
|
+
const dimensions = needsDrawingLayout ? readXlsxDrawingLayout(rootOf(parsePart(parts[path], path), spreadNs, "worksheet"), sheetId)(options.drawingDigitWidth) : undefined;
|
|
200
|
+
parts[drawingPath] = writeXlsxDrawing(frames, dimensions);
|
|
201
|
+
const entry = relationshipsPath(drawingPath);
|
|
202
|
+
if (after.length || nextPictures.length) parts[entry] = writeXlsxDrawingRelationships([...after, ...nextPictures]);
|
|
203
|
+
else delete parts[entry];
|
|
204
|
+
}
|
|
205
|
+
if (!native) {
|
|
206
|
+
const relationships = editPartRelationships(parts, path);
|
|
207
|
+
if ([...relationships.entries.values()].some(relation => relation.type !== hyperlinkRelationship || relation.path !== null)) {
|
|
208
|
+
throw new Error("工作表的绘图关系无法安全替换。");
|
|
209
|
+
}
|
|
210
|
+
const relationshipId = relationships.add(relationshipNs + "/drawing", "/" + drawingPath.split("/").map(encodeURIComponent).join("/"));
|
|
211
|
+
relationships.write();
|
|
212
|
+
writeWorksheetDrawing(parts, path, relationshipId);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
images.collectUnused(remove);
|
|
216
|
+
if (manifestChanged) parts[manifestPath] = writePart(manifest);
|
|
217
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { mapWorkbookExternalReferences, sameWorkbookExternalLink, type WorkbookExternalLink } from "@quirekit/workbook";
|
|
2
|
+
|
|
3
|
+
/** @param links - Directory in the actual native export order. @returns Checks references against available source sheets. */
|
|
4
|
+
export function xlsxExternalFormulaCheck(links: readonly WorkbookExternalLink[] = []) {
|
|
5
|
+
const names = new Map(links.map(link => [link.slot, new Set(link.sheets.map(sheet => sheet.name.toUpperCase()))]));
|
|
6
|
+
/** @param formula - Native worksheet expression. @returns Whether all external qualifiers resolve against the directory. */
|
|
7
|
+
return function supports(formula: string): boolean {
|
|
8
|
+
let read = false, supported = true;
|
|
9
|
+
const { complete } = mapWorkbookExternalReferences(formula, ({ slot, range }) => {
|
|
10
|
+
read = true;
|
|
11
|
+
if (!names.get(slot)?.has(range.sheetId.toUpperCase())) supported = false;
|
|
12
|
+
return undefined;
|
|
13
|
+
});
|
|
14
|
+
return complete && read && supported;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param before - Original archive sources. @param after - Published sources. @returns Whether an external part or ordinal changed. */
|
|
19
|
+
export function xlsxExternalLinksChanged(before: readonly WorkbookExternalLink[] = [], after: readonly WorkbookExternalLink[] = []): boolean {
|
|
20
|
+
return before.length !== after.length || before.some((source, index) => !sameWorkbookExternalLink(source, after[index]));
|
|
21
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { createXlsx } from "../create";
|
|
5
|
+
import { openXlsx } from "../package/read";
|
|
6
|
+
|
|
7
|
+
const fixture = readFileSync(new URL("../../fixtures/external-links/cached-report.xlsx", import.meta.url));
|
|
8
|
+
|
|
9
|
+
it("uses native slot order and retains untouched relationship parts through ordinary edits", () => {
|
|
10
|
+
const file = openXlsx("回款报告", fixture);
|
|
11
|
+
expect(file.restrictions).toEqual([]);
|
|
12
|
+
expect(file.snapshot.externalLinks?.map(({ slot, name }) => [slot, name])).toEqual([[1, "receivables.xlsx"], [2, "previous.xlsx"]]);
|
|
13
|
+
expect(file.snapshot.externalLinks?.[0]?.sheets).toMatchObject([
|
|
14
|
+
{ name: "目录", cells: [] },
|
|
15
|
+
{ name: "回款 明细", cells: [
|
|
16
|
+
{ row: 1, column: 1, result: { status: "value", value: 7 } },
|
|
17
|
+
{ result: { status: "value", value: 13 } }, { result: { status: "value", value: null } },
|
|
18
|
+
{ result: { status: "value", value: "0007" } }, { result: { status: "error", code: "#N/A" } }
|
|
19
|
+
] }
|
|
20
|
+
]);
|
|
21
|
+
const snapshot = file.snapshot;
|
|
22
|
+
const [sheet] = snapshot.sheets;
|
|
23
|
+
const bytes = file.write({ ...snapshot, revision: 1, sheets: [
|
|
24
|
+
{ ...sheet!, cells: sheet!.cells.map(cell => cell.row === 0 && cell.column === 1
|
|
25
|
+
? { ...cell, input: { kind: "value", value: 30 } } : cell) }
|
|
26
|
+
] }, { result: ({ row }) => ({ status: "value", value: row === 3 ? 41 : 20 }) });
|
|
27
|
+
const original = unzipSync(fixture), saved = unzipSync(bytes);
|
|
28
|
+
for (const path of Object.keys(original).filter(path => path.startsWith("xl/externalLinks/"))) {
|
|
29
|
+
expect(saved[path]).toEqual(original[path]);
|
|
30
|
+
}
|
|
31
|
+
expect(strFromU8(saved["xl/worksheets/sheet1.xml"]!)).toMatch(/<f>A2-A3\+B1<\/f><v>41<\/v>/u);
|
|
32
|
+
expect(openXlsx("回款报告", bytes).snapshot.externalLinks).toEqual(snapshot.externalLinks);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("keeps a workbook with an unrecognized link part or formula qualifier as the original file", () => {
|
|
36
|
+
const parts = unzipSync(fixture);
|
|
37
|
+
const path = "xl/externalLinks/externalLink1.xml";
|
|
38
|
+
parts[path] = strToU8(strFromU8(parts[path]!).replace('sheetId="1"', 'sheetId="10"'));
|
|
39
|
+
const bytes = zipSync(parts);
|
|
40
|
+
const file = openXlsx("失效来源", bytes);
|
|
41
|
+
expect(file.restrictions).toContain("暂未支持的外部工作簿部件");
|
|
42
|
+
expect(file.snapshot.externalLinks).toBeUndefined();
|
|
43
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
44
|
+
|
|
45
|
+
const foreign = unzipSync(fixture);
|
|
46
|
+
const sheet = "xl/worksheets/sheet1.xml";
|
|
47
|
+
foreign[sheet] = strToU8(strFromU8(foreign[sheet]!).replace("[1]", "[5]"));
|
|
48
|
+
expect(openXlsx("未知来源", zipSync(foreign)).restrictions).toContain("外部工作簿引用");
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("saves formulas against the original source directory and rejects dangling native links", () => {
|
|
52
|
+
const file = openXlsx("回款报告", fixture);
|
|
53
|
+
const { snapshot } = file;
|
|
54
|
+
const sheet = snapshot.sheets[0]!;
|
|
55
|
+
const formula = "='[2]回款 明细'!$B$2";
|
|
56
|
+
const linked = { ...snapshot, sheets: [{ ...sheet, cells: [
|
|
57
|
+
...sheet.cells, { row: 0, column: 2, input: { kind: "formula" as const, formula } }
|
|
58
|
+
] }] };
|
|
59
|
+
expect(openXlsx("新增引用", file.write(linked)).restrictions).toEqual([]);
|
|
60
|
+
|
|
61
|
+
const withoutSource = { ...linked, externalLinks: undefined };
|
|
62
|
+
expect(() => createXlsx(withoutSource)).toThrow("公式中的外部引用缺少原生来源工作簿或工作表");
|
|
63
|
+
const unknownSheet = { ...linked, sheets: [{ ...sheet, cells: [
|
|
64
|
+
...sheet.cells, { row: 0, column: 2, input: { kind: "formula" as const, formula: "='[1]不存在的工作表'!A1" } }
|
|
65
|
+
] }] };
|
|
66
|
+
expect(() => file.write(unknownSheet)).toThrow("公式中的外部引用缺少原生来源工作簿或工作表");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("writes newly selected file links and refreshes an imported cache without changing its external relationship", () => {
|
|
70
|
+
const input = openXlsx("来源缓存", fixture);
|
|
71
|
+
const first = input.snapshot.externalLinks![0]!;
|
|
72
|
+
const sheet = first.sheets[1]!;
|
|
73
|
+
const refreshed = { ...first, sheets: [first.sheets[0]!, { ...sheet, cells: [
|
|
74
|
+
{ row: 1, column: 1, result: { status: "value" as const, value: 67 } }, ...sheet.cells.slice(1)
|
|
75
|
+
] }] };
|
|
76
|
+
const bytes = input.write({ ...input.snapshot, externalLinks: [refreshed, input.snapshot.externalLinks![1]!] });
|
|
77
|
+
const saved = unzipSync(bytes);
|
|
78
|
+
const original = unzipSync(fixture);
|
|
79
|
+
expect(saved["xl/externalLinks/_rels/externalLink1.xml.rels"]).toEqual(original["xl/externalLinks/_rels/externalLink1.xml.rels"]);
|
|
80
|
+
expect(saved["xl/externalLinks/externalLink2.xml"]).toEqual(original["xl/externalLinks/externalLink2.xml"]);
|
|
81
|
+
expect(openXlsx("更新", bytes).snapshot.externalLinks?.[0]).toEqual(refreshed);
|
|
82
|
+
|
|
83
|
+
const name = "回款 十月#.xlsx";
|
|
84
|
+
const local = createXlsx({ ...input.snapshot, sheets: [{ ...input.snapshot.sheets[0]!, cells: [
|
|
85
|
+
{ row: 0, column: 0, input: { kind: "formula", formula: "='[1]回款 明细'!$B$2" } }
|
|
86
|
+
] }], externalLinks: [{ ...refreshed, name, localFile: true }], formulaResults: undefined });
|
|
87
|
+
const native = unzipSync(local);
|
|
88
|
+
expect(strFromU8(native["xl/externalLinks/_rels/externalLink1.xml.rels"]!)).toContain(`Target="${encodeURIComponent(name)}"`);
|
|
89
|
+
expect(strFromU8(native["xl/externalLinks/externalLink1.xml"]!)).toContain('<sheetData sheetId="1">');
|
|
90
|
+
const reopened = openXlsx("新文件", local);
|
|
91
|
+
expect(reopened.restrictions).toEqual([]);
|
|
92
|
+
expect(reopened.snapshot.externalLinks?.[0]).toEqual({ ...refreshed, name });
|
|
93
|
+
});
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { copyWorkbookExternalLinks, isWorkbookSpreadsheetErrorCode, parseWorkbookRange,
|
|
3
|
+
workbookExternalCacheCells, workbookExternalLinkLimit, workbookExternalSheetLimit, type WorkbookExternalCell, type WorkbookExternalLink } from "@quirekit/workbook";
|
|
4
|
+
import { readRelationships, relationshipsPath } from "../opc/relationships";
|
|
5
|
+
import type { PackageRelationship } from "../opc/types";
|
|
6
|
+
import { child, children, parsePart, readIndex, relationshipNs, rootOf, spreadNs } from "../opc/xml";
|
|
7
|
+
import { readXlsxFormulaCache } from "../worksheet/formula/cache";
|
|
8
|
+
import { xlsxExternalFormulaCheck } from "./formulas";
|
|
9
|
+
import type { XlsxExternalLinkParts } from "./types";
|
|
10
|
+
|
|
11
|
+
/** @param name - Original OPC target. @param slot - One-based fallback identity. @returns Display label without a path or URL parameters. */
|
|
12
|
+
function sourceName(name: string, slot: number): string {
|
|
13
|
+
const leaf = (name.split(/[?#]/u)[0] ?? "").split(/[/\\]/u).pop() ?? "";
|
|
14
|
+
try {
|
|
15
|
+
const decoded = decodeURIComponent(leaf);
|
|
16
|
+
if (decoded && decoded.length <= 255 && !/[\u0000-\u001f/\\]/u.test(decoded)) return decoded;
|
|
17
|
+
} catch { /* The source location stays in the retained native part. */ }
|
|
18
|
+
return "来源工作簿 " + slot;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param cell - Native external sheet cache record. @param row - Expected zero-based container row. @returns The typed, explicitly cached value. */
|
|
22
|
+
function readCell(cell: Element, row: number): WorkbookExternalCell {
|
|
23
|
+
const address = cell.getAttribute("r");
|
|
24
|
+
if (!address || !/^[A-Z]{1,3}[1-9]\d{0,6}$/u.test(address)) throw unsupported();
|
|
25
|
+
const range = parseWorkbookRange("", address);
|
|
26
|
+
if (range.startRow !== row || children(cell).some(node => node.localName !== "v") || children(cell, "v").length > 1) throw unsupported();
|
|
27
|
+
const type = cell.getAttribute("t") || "n";
|
|
28
|
+
if (!["n", "b", "e", "str"].includes(type)) throw unsupported();
|
|
29
|
+
const value = child(cell, "v")?.textContent;
|
|
30
|
+
if (type === "b" && !["0", "1", "false", "true"].includes(value ?? "")) throw unsupported();
|
|
31
|
+
const result = type === "n" && !value ? { status: "value", value: null } as const : readXlsxFormulaCache(cell, []);
|
|
32
|
+
if (result.status === "unavailable" || result.status === "error" && !isWorkbookSpreadsheetErrorCode(result.code)) throw unsupported();
|
|
33
|
+
return { row, column: range.startColumn, result };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param parts - Original XLSX archive.
|
|
38
|
+
* @param workbook - Workbook XML, which owns the one-based link ordinals.
|
|
39
|
+
* @param relations - Validated relationships addressing parts within the package.
|
|
40
|
+
* @param restrictions - File preservation reasons reported by the normal opener.
|
|
41
|
+
* @returns The known native links and the formulas that may use those slots.
|
|
42
|
+
*/
|
|
43
|
+
export function readXlsxExternalLinks(parts: Readonly<Record<string, Uint8Array>>, workbook: Element,
|
|
44
|
+
relations: ReadonlyMap<string, PackageRelationship>, restrictions: Set<string>) {
|
|
45
|
+
const references = child(workbook, "externalReferences");
|
|
46
|
+
if (!references) return undefined;
|
|
47
|
+
try {
|
|
48
|
+
const entries = children(references);
|
|
49
|
+
if (!entries.length || entries.length > workbookExternalLinkLimit || entries.some(node => node.localName !== "externalReference")) throw unsupported();
|
|
50
|
+
let sheetsRead = 0, cellsRead = 0;
|
|
51
|
+
const ids = new Set<string>();
|
|
52
|
+
const native: XlsxExternalLinkParts[] = [];
|
|
53
|
+
const links = copyWorkbookExternalLinks(entries.map((entry, index): WorkbookExternalLink => {
|
|
54
|
+
const id = entry.getAttributeNS(relationshipNs, "id");
|
|
55
|
+
const relation = id ? relations.get(id) : undefined;
|
|
56
|
+
if (!relation?.path || relation.type !== relationshipNs + "/externalLink" || ids.has(relation.id)) throw unsupported();
|
|
57
|
+
ids.add(relation.id);
|
|
58
|
+
const path = relation.path;
|
|
59
|
+
const root = rootOf(parsePart(parts[path], path), spreadNs, "externalLink");
|
|
60
|
+
const book = child(root, "externalBook");
|
|
61
|
+
if (!book || children(root).length !== 1 || children(book).some(node =>
|
|
62
|
+
node.localName !== "sheetNames" && node.localName !== "sheetDataSet"
|
|
63
|
+
&& !(node.localName === "definedNames" && children(node).length === 0))) throw unsupported();
|
|
64
|
+
const relationshipPart = relationshipsPath(path);
|
|
65
|
+
const external = readRelationships(parsePart(parts[relationshipPart], relationshipPart), path)
|
|
66
|
+
.get(book.getAttributeNS(relationshipNs, "id") ?? "");
|
|
67
|
+
if (!external || external.type !== relationshipNs + "/externalLinkPath" || external.path !== null) throw unsupported();
|
|
68
|
+
native.push({ id: relation.id, path, targetId: external.id });
|
|
69
|
+
const names = child(book, "sheetNames");
|
|
70
|
+
const directory = names ? children(names) : [];
|
|
71
|
+
if (children(book, "sheetNames").length !== 1 || children(book, "sheetDataSet").length > 1
|
|
72
|
+
|| directory.some(node => node.localName !== "sheetName")) throw unsupported();
|
|
73
|
+
sheetsRead += directory.length;
|
|
74
|
+
if (!directory.length || sheetsRead > workbookExternalSheetLimit) throw unsupported();
|
|
75
|
+
const sheets = directory.map(node => ({ name: node.getAttribute("val") ?? "", cells: [] as WorkbookExternalCell[] }));
|
|
76
|
+
const cache = child(book, "sheetDataSet");
|
|
77
|
+
const listed = new Set<number>();
|
|
78
|
+
for (const sheet of cache ? children(cache) : []) {
|
|
79
|
+
const index = readIndex(sheet, "sheetId");
|
|
80
|
+
if (sheet.localName !== "sheetData" || index === undefined || listed.has(index)) throw unsupported();
|
|
81
|
+
const target = sheets[index];
|
|
82
|
+
if (!target) throw unsupported();
|
|
83
|
+
listed.add(index);
|
|
84
|
+
for (const node of children(sheet)) {
|
|
85
|
+
const row = readIndex(node, "r");
|
|
86
|
+
if (node.localName !== "row" || row === undefined || row < 1) throw unsupported();
|
|
87
|
+
for (const cell of children(node)) {
|
|
88
|
+
if (cell.localName !== "cell" || ++cellsRead > workbookExternalCacheCells) throw unsupported();
|
|
89
|
+
target.cells.push(readCell(cell, row - 1));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const slot = index + 1;
|
|
94
|
+
return { slot, name: sourceName(external.element.getAttribute("Target") ?? "", slot), sheets };
|
|
95
|
+
}));
|
|
96
|
+
return { links, ids, native, supports: xlsxExternalFormulaCheck(links) };
|
|
97
|
+
} catch {
|
|
98
|
+
restrictions.add("暂未支持的外部工作簿部件");
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** @returns A reason to preserve the unhandled native external parts. */
|
|
104
|
+
function unsupported(): Error { return new Error("不支持的外部工作簿缓存。"); }
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Owned native parts for one workbook link, in formula ordinal order. */
|
|
2
|
+
export interface XlsxExternalLinkParts {
|
|
3
|
+
/** Relationship from the workbook to the cache part. */
|
|
4
|
+
readonly id: string;
|
|
5
|
+
/** Cache part inside the destination archive. */
|
|
6
|
+
readonly path: string;
|
|
7
|
+
/** Relationship from the cache part to the source file. */
|
|
8
|
+
readonly targetId: string;
|
|
9
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { strToU8 } from "fflate";
|
|
3
|
+
import { copyWorkbookExternalLinks, formatWorkbookColumn, sameWorkbookExternalLink, type WorkbookExternalLink } from "@quirekit/workbook";
|
|
4
|
+
import { verifyXlsxPartOwnership } from "../opc/ownership";
|
|
5
|
+
import { editPartRelationships, relationshipsPath } from "../opc/relationships";
|
|
6
|
+
import { child, children, contentTypeNs, parsePart, relationshipNs, rootOf, spreadNs, writePart } from "../opc/xml";
|
|
7
|
+
import type { XlsxPackage } from "../package/types";
|
|
8
|
+
import { encodeXlsxText, insertXlsxText } from "../worksheet/text";
|
|
9
|
+
|
|
10
|
+
const externalLinkType = "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml";
|
|
11
|
+
|
|
12
|
+
/** @param link - Published directory and sparse values. @param targetId - Its external relationship. @returns Native link cache part. */
|
|
13
|
+
function writeCache(link: WorkbookExternalLink, targetId: string): Uint8Array {
|
|
14
|
+
const document = parsePart(strToU8(`<externalLink xmlns="${spreadNs}" xmlns:r="${relationshipNs}"/>`), "externalLink");
|
|
15
|
+
const root = rootOf(document, spreadNs, "externalLink");
|
|
16
|
+
const book = document.createElementNS(spreadNs, "externalBook");
|
|
17
|
+
book.setAttributeNS(relationshipNs, "r:id", targetId);
|
|
18
|
+
root.appendChild(book);
|
|
19
|
+
const names = document.createElementNS(spreadNs, "sheetNames");
|
|
20
|
+
const data = document.createElementNS(spreadNs, "sheetDataSet");
|
|
21
|
+
book.appendChild(names);
|
|
22
|
+
book.appendChild(data);
|
|
23
|
+
for (const [index, sheet] of link.sheets.entries()) {
|
|
24
|
+
const name = document.createElementNS(spreadNs, "sheetName");
|
|
25
|
+
name.setAttribute("val", sheet.name);
|
|
26
|
+
names.appendChild(name);
|
|
27
|
+
if (!sheet.cells.length) continue;
|
|
28
|
+
const container = document.createElementNS(spreadNs, "sheetData");
|
|
29
|
+
container.setAttribute("sheetId", String(index));
|
|
30
|
+
data.appendChild(container);
|
|
31
|
+
let currentRow: Element | undefined;
|
|
32
|
+
let previous = -1;
|
|
33
|
+
for (const { row, column, result } of [...sheet.cells].sort((a, b) => a.row - b.row || a.column - b.column)) {
|
|
34
|
+
if (row !== previous || !currentRow) {
|
|
35
|
+
currentRow = document.createElementNS(spreadNs, "row");
|
|
36
|
+
currentRow.setAttribute("r", String(row + 1));
|
|
37
|
+
container.appendChild(currentRow);
|
|
38
|
+
previous = row;
|
|
39
|
+
}
|
|
40
|
+
const cell = document.createElementNS(spreadNs, "cell");
|
|
41
|
+
cell.setAttribute("r", formatWorkbookColumn(column) + String(row + 1));
|
|
42
|
+
currentRow.appendChild(cell);
|
|
43
|
+
if (result.status === "error") {
|
|
44
|
+
cell.setAttribute("t", "e");
|
|
45
|
+
insertXlsxText(document, cell, "v", result.code);
|
|
46
|
+
} else if (result.value !== null) {
|
|
47
|
+
const { value } = result;
|
|
48
|
+
cell.setAttribute("t", typeof value === "string" ? "str" : typeof value === "boolean" ? "b" : "n");
|
|
49
|
+
insertXlsxText(document, cell, "v", typeof value === "string" ? encodeXlsxText(value) : typeof value === "boolean" ? String(Number(value)) : String(value));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return writePart(document);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** @param source - Original workbook and native directory. @param parts - Staged package. @param workbook - Staged workbook XML.
|
|
57
|
+
* @param directory - Source bindings in stable formula order. */
|
|
58
|
+
export function writeXlsxExternalLinks(source: XlsxPackage, parts: Record<string, Uint8Array>, workbook: Element,
|
|
59
|
+
directory: readonly WorkbookExternalLink[] = []): void {
|
|
60
|
+
const links = copyWorkbookExternalLinks(directory);
|
|
61
|
+
const original = source.baseline?.externalLinks ?? [];
|
|
62
|
+
const modified = (source.externalLinkParts ?? []).filter((_, index) => !sameWorkbookExternalLink(original[index], links[index]));
|
|
63
|
+
if (modified.length) verifyXlsxPartOwnership(source.parts,
|
|
64
|
+
new Map(modified.map(({ path }) => [path, new Set([source.workbookPath])])), new Map(modified.map(({ path }) => [path, externalLinkType])));
|
|
65
|
+
|
|
66
|
+
const document = workbook.ownerDocument!;
|
|
67
|
+
const existing = child(workbook, "externalReferences");
|
|
68
|
+
const references = existing ?? document.createElementNS(spreadNs, "externalReferences");
|
|
69
|
+
const entries = children(references);
|
|
70
|
+
const relationships = editPartRelationships(parts, source.workbookPath);
|
|
71
|
+
const manifest = parsePart(parts["[Content_Types].xml"], "[Content_Types].xml");
|
|
72
|
+
const types = rootOf(manifest, contentTypeNs, "Types");
|
|
73
|
+
const prefix = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
|
|
74
|
+
const occupied = new Set(Object.keys(parts).map(path => path.toLowerCase()));
|
|
75
|
+
|
|
76
|
+
// Keep existing ordinals and unrelated parts. New sources get fresh IDs and paths in this archive.
|
|
77
|
+
for (const [index, link] of links.entries()) {
|
|
78
|
+
const previous = source.externalLinkParts?.[index];
|
|
79
|
+
if (previous && sameWorkbookExternalLink(original[index], link)) continue;
|
|
80
|
+
if ((!previous || original[index]?.name !== link.name) && !link.localFile) {
|
|
81
|
+
throw new Error("保存跨工作簿引用需要原始来源关系或已选择的本地 XLSX 文件。");
|
|
82
|
+
}
|
|
83
|
+
let relative = `externalLinks/externalLink${link.slot}.xml`;
|
|
84
|
+
for (let serial = links.length + 1; !previous && (occupied.has((prefix + relative).toLowerCase())
|
|
85
|
+
|| occupied.has(relationshipsPath(prefix + relative).toLowerCase())); serial++) relative = `externalLinks/externalLink${serial}.xml`;
|
|
86
|
+
const path = previous?.path ?? prefix + relative;
|
|
87
|
+
const target = editPartRelationships(parts, path);
|
|
88
|
+
const file = link.localFile ? encodeURIComponent(link.name) : undefined;
|
|
89
|
+
const targetId = previous?.targetId ?? target.add(relationshipNs + "/externalLinkPath", file!, true);
|
|
90
|
+
if (file && previous) target.entries.get(targetId)?.element.setAttribute("Target", file);
|
|
91
|
+
if (file || !previous) target.write();
|
|
92
|
+
parts[path] = writeCache(link, targetId);
|
|
93
|
+
if (previous) continue;
|
|
94
|
+
occupied.add(path.toLowerCase());
|
|
95
|
+
const entry = document.createElementNS(spreadNs, "externalReference");
|
|
96
|
+
entry.setAttributeNS(relationshipNs, "r:id", relationships.add(relationshipNs + "/externalLink", relative));
|
|
97
|
+
references.appendChild(entry);
|
|
98
|
+
const override = manifest.createElementNS(contentTypeNs, "Override");
|
|
99
|
+
override.setAttribute("PartName", "/" + path);
|
|
100
|
+
override.setAttribute("ContentType", externalLinkType);
|
|
101
|
+
types.appendChild(override);
|
|
102
|
+
}
|
|
103
|
+
for (const prior of source.externalLinkParts?.slice(links.length) ?? []) {
|
|
104
|
+
delete parts[prior.path];
|
|
105
|
+
delete parts[relationshipsPath(prior.path)];
|
|
106
|
+
relationships.remove(prior.id);
|
|
107
|
+
const override = children(types, "Override").find(node => node.getAttribute("PartName") === "/" + prior.path);
|
|
108
|
+
if (override) types.removeChild(override);
|
|
109
|
+
}
|
|
110
|
+
for (const entry of entries.slice(links.length)) references.removeChild(entry);
|
|
111
|
+
if (!links.length && existing) workbook.removeChild(existing);
|
|
112
|
+
else if (links.length && !existing) {
|
|
113
|
+
const preceding = child(workbook, "functionGroups") ?? child(workbook, "sheets")!;
|
|
114
|
+
workbook.insertBefore(references, preceding.nextSibling);
|
|
115
|
+
}
|
|
116
|
+
if (links.length !== original.length) {
|
|
117
|
+
relationships.write();
|
|
118
|
+
parts["[Content_Types].xml"] = writePart(manifest);
|
|
119
|
+
}
|
|
120
|
+
}
|