@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.
Files changed (336) hide show
  1. package/LICENSE.md +21 -0
  2. package/THIRD_PARTY_NOTICES.md +150 -0
  3. package/dist/index.d.mts +122 -0
  4. package/dist/index.d.mts.map +1 -0
  5. package/dist/index.mjs +19167 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/licenses/saxes.LICENSE +64 -0
  8. package/licenses/xmlchars.LICENSE +18 -0
  9. package/package.json +52 -3
  10. package/src/bundle.ts +17 -0
  11. package/src/comments/legacy/read.ts +68 -0
  12. package/src/comments/legacy/write.ts +64 -0
  13. package/src/comments/package/ranges.ts +78 -0
  14. package/src/comments/package/read.ts +95 -0
  15. package/src/comments/package/roundtrip.test.ts +106 -0
  16. package/src/comments/package/write.ts +130 -0
  17. package/src/comments/thread/read.ts +69 -0
  18. package/src/comments/thread/write.ts +61 -0
  19. package/src/comments/types.ts +43 -0
  20. package/src/comments/xml.ts +50 -0
  21. package/src/create.ts +13 -0
  22. package/src/drawing/cache.ts +48 -0
  23. package/src/drawing/chart.test.ts +96 -0
  24. package/src/drawing/chart.ts +87 -0
  25. package/src/drawing/definition/plots.ts +76 -0
  26. package/src/drawing/definition/read.ts +65 -0
  27. package/src/drawing/definition/shape.ts +40 -0
  28. package/src/drawing/definition/types.ts +24 -0
  29. package/src/drawing/editable-picture.ts +80 -0
  30. package/src/drawing/graph.ts +148 -0
  31. package/src/drawing/identity.ts +22 -0
  32. package/src/drawing/import.ts +133 -0
  33. package/src/drawing/namespaces.ts +11 -0
  34. package/src/drawing/picture.test.ts +98 -0
  35. package/src/drawing/picture.ts +54 -0
  36. package/src/drawing/placement/anchor.ts +71 -0
  37. package/src/drawing/placement/axes.ts +113 -0
  38. package/src/drawing/placement/marker.ts +16 -0
  39. package/src/drawing/placement/transform.ts +132 -0
  40. package/src/drawing/placement/types.ts +20 -0
  41. package/src/drawing/presentation/cartesian/axes.ts +103 -0
  42. package/src/drawing/presentation/cartesian/plot.ts +109 -0
  43. package/src/drawing/presentation/cartesian/types.ts +9 -0
  44. package/src/drawing/presentation/layout.ts +29 -0
  45. package/src/drawing/presentation/paint.ts +56 -0
  46. package/src/drawing/presentation/properties.ts +31 -0
  47. package/src/drawing/read.ts +85 -0
  48. package/src/drawing/shapes/connector.ts +55 -0
  49. package/src/drawing/shapes/paint.ts +108 -0
  50. package/src/drawing/shapes/read.ts +89 -0
  51. package/src/drawing/shapes/text.ts +89 -0
  52. package/src/drawing/shapes/types.ts +13 -0
  53. package/src/drawing/sources.test.ts +27 -0
  54. package/src/drawing/sources.ts +43 -0
  55. package/src/drawing/types.ts +54 -0
  56. package/src/drawing/worksheet-connector.test.ts +135 -0
  57. package/src/drawing/worksheet-shape.test.ts +61 -0
  58. package/src/drawing/write/anchor.ts +17 -0
  59. package/src/drawing/write/axes.ts +23 -0
  60. package/src/drawing/write/chart.ts +56 -0
  61. package/src/drawing/write/drawing.ts +61 -0
  62. package/src/drawing/write/pictures.ts +68 -0
  63. package/src/drawing/write/series.ts +43 -0
  64. package/src/drawing/write/shapes.ts +113 -0
  65. package/src/drawing/write/text.ts +26 -0
  66. package/src/drawing/write/workbook.test.ts +199 -0
  67. package/src/drawing/write/workbook.ts +217 -0
  68. package/src/external-links/formulas.ts +21 -0
  69. package/src/external-links/read.test.ts +93 -0
  70. package/src/external-links/read.ts +104 -0
  71. package/src/external-links/types.ts +9 -0
  72. package/src/external-links/write.ts +120 -0
  73. package/src/image/excel.ts +122 -0
  74. package/src/image/native.ts +21 -0
  75. package/src/image/ownership.ts +77 -0
  76. package/src/image/parts.ts +45 -0
  77. package/src/image/raster.ts +25 -0
  78. package/src/image/read.test.ts +95 -0
  79. package/src/image/read.ts +66 -0
  80. package/src/image/relationships.ts +26 -0
  81. package/src/image/types.ts +48 -0
  82. package/src/image/wps.ts +43 -0
  83. package/src/image/write.test.ts +53 -0
  84. package/src/image/write.ts +118 -0
  85. package/src/index.ts +6 -0
  86. package/src/metadata/dynamic-array.ts +105 -0
  87. package/src/metadata/package.ts +75 -0
  88. package/src/metadata/types.ts +7 -0
  89. package/src/opc/archive.ts +26 -0
  90. package/src/opc/ownership.ts +40 -0
  91. package/src/opc/relationships.ts +98 -0
  92. package/src/opc/revision.ts +28 -0
  93. package/src/opc/shape.ts +23 -0
  94. package/src/opc/types.ts +13 -0
  95. package/src/opc/xml.test.ts +49 -0
  96. package/src/opc/xml.ts +128 -0
  97. package/src/optimization/blanks.ts +53 -0
  98. package/src/optimization/optimize.test.ts +117 -0
  99. package/src/optimization/optimize.ts +41 -0
  100. package/src/optimization/package.ts +65 -0
  101. package/src/optimization/rules.ts +46 -0
  102. package/src/optimization/styles.ts +76 -0
  103. package/src/optimization/types.ts +33 -0
  104. package/src/package/assembly.test.ts +117 -0
  105. package/src/package/calculation-metadata.test.ts +85 -0
  106. package/src/package/calculation-metadata.ts +88 -0
  107. package/src/package/checkboxes.ts +37 -0
  108. package/src/package/cleanup.test.ts +61 -0
  109. package/src/package/dashboard.test.ts +53 -0
  110. package/src/package/dashboard.ts +84 -0
  111. package/src/package/extensions.ts +16 -0
  112. package/src/package/merge-recipes.ts +84 -0
  113. package/src/package/names/conditional.ts +64 -0
  114. package/src/package/names/defined.test.ts +52 -0
  115. package/src/package/names/defined.ts +75 -0
  116. package/src/package/names/filter.ts +68 -0
  117. package/src/package/names/print-layout.ts +62 -0
  118. package/src/package/names/print.ts +62 -0
  119. package/src/package/new.ts +46 -0
  120. package/src/package/open/appearance.ts +46 -0
  121. package/src/package/open/directory.ts +61 -0
  122. package/src/package/open/restrictions.ts +27 -0
  123. package/src/package/open/snapshot.test.ts +48 -0
  124. package/src/package/open/snapshot.ts +34 -0
  125. package/src/package/open/source-write.ts +130 -0
  126. package/src/package/open/types.ts +73 -0
  127. package/src/package/open/worksheets.ts +149 -0
  128. package/src/package/positions.ts +40 -0
  129. package/src/package/read.ts +143 -0
  130. package/src/package/save/types.ts +57 -0
  131. package/src/package/save/worksheets.ts +126 -0
  132. package/src/package/selection-copy.test.ts +70 -0
  133. package/src/package/styles.ts +39 -0
  134. package/src/package/types.ts +52 -0
  135. package/src/package/workbook-views.ts +34 -0
  136. package/src/package/worksheets.test.ts +190 -0
  137. package/src/package/worksheets.ts +162 -0
  138. package/src/package/write.ts +175 -0
  139. package/src/pivot/cache/calculated.ts +34 -0
  140. package/src/pivot/cache/dates.ts +124 -0
  141. package/src/pivot/cache/groups.ts +11 -0
  142. package/src/pivot/cache/members.ts +99 -0
  143. package/src/pivot/cache/numbers.ts +63 -0
  144. package/src/pivot/cache/read.ts +131 -0
  145. package/src/pivot/cache/time.ts +20 -0
  146. package/src/pivot/cache/values.ts +43 -0
  147. package/src/pivot/cache/write.ts +117 -0
  148. package/src/pivot/definition/axes.ts +35 -0
  149. package/src/pivot/definition/dates.ts +87 -0
  150. package/src/pivot/definition/display.ts +86 -0
  151. package/src/pivot/definition/extension.ts +57 -0
  152. package/src/pivot/definition/field-settings/caption.ts +38 -0
  153. package/src/pivot/definition/field-settings/comparison.ts +47 -0
  154. package/src/pivot/definition/field-settings/field.ts +66 -0
  155. package/src/pivot/definition/field-settings/filters.ts +86 -0
  156. package/src/pivot/definition/field-settings/measure.ts +79 -0
  157. package/src/pivot/definition/field-settings/types.ts +19 -0
  158. package/src/pivot/definition/functions.ts +21 -0
  159. package/src/pivot/definition/items.ts +144 -0
  160. package/src/pivot/definition/members.ts +98 -0
  161. package/src/pivot/definition/numbers.ts +19 -0
  162. package/src/pivot/definition/presentation.ts +52 -0
  163. package/src/pivot/definition/read.ts +143 -0
  164. package/src/pivot/definition/report-layout.ts +39 -0
  165. package/src/pivot/definition/write.ts +157 -0
  166. package/src/pivot/package/calculated.test.ts +103 -0
  167. package/src/pivot/package/dates.test.ts +266 -0
  168. package/src/pivot/package/display.test.ts +133 -0
  169. package/src/pivot/package/field-settings.test.ts +59 -0
  170. package/src/pivot/package/layout.test.ts +148 -0
  171. package/src/pivot/package/measure-settings.test.ts +85 -0
  172. package/src/pivot/package/members.test.ts +167 -0
  173. package/src/pivot/package/numbers.test.ts +120 -0
  174. package/src/pivot/package/read.ts +93 -0
  175. package/src/pivot/package/roundtrip.test.ts +244 -0
  176. package/src/pivot/package/write.ts +103 -0
  177. package/src/pivot/types.ts +36 -0
  178. package/src/pivot/xml.ts +50 -0
  179. package/src/presentation.test.ts +186 -0
  180. package/src/roundtrip.test.ts +72 -0
  181. package/src/styles/checkbox/bags.ts +85 -0
  182. package/src/styles/checkbox/style.ts +45 -0
  183. package/src/styles/checkbox/types.ts +7 -0
  184. package/src/styles/color.ts +64 -0
  185. package/src/styles/differential-preview.ts +60 -0
  186. package/src/styles/differential.ts +119 -0
  187. package/src/styles/numbers.ts +9 -0
  188. package/src/styles/parts.ts +107 -0
  189. package/src/styles/read.ts +95 -0
  190. package/src/styles/reference.ts +14 -0
  191. package/src/styles/types.ts +9 -0
  192. package/src/styles/write.test.ts +88 -0
  193. package/src/styles/write.ts +162 -0
  194. package/src/table/conversion.test.ts +73 -0
  195. package/src/table/definition.ts +89 -0
  196. package/src/table/filter.ts +42 -0
  197. package/src/table/ownership.ts +112 -0
  198. package/src/table/read.test.ts +274 -0
  199. package/src/table/read.ts +117 -0
  200. package/src/table/remove.ts +55 -0
  201. package/src/table/sort.test.ts +79 -0
  202. package/src/table/styles/builtin.ts +40 -0
  203. package/src/table/styles/differential.ts +55 -0
  204. package/src/table/styles/preset-data.ts +17 -0
  205. package/src/table/styles/presets/dark.ts +104 -0
  206. package/src/table/styles/presets/light-grid.ts +68 -0
  207. package/src/table/styles/presets/light.ts +145 -0
  208. package/src/table/styles/presets/medium-edges.ts +131 -0
  209. package/src/table/styles/presets/medium.ts +131 -0
  210. package/src/table/styles/read.ts +70 -0
  211. package/src/table/styles/types.ts +27 -0
  212. package/src/table/totals.test.ts +77 -0
  213. package/src/table/totals.ts +79 -0
  214. package/src/table/types.ts +21 -0
  215. package/src/table/write.ts +189 -0
  216. package/src/types.ts +74 -0
  217. package/src/value/date.ts +21 -0
  218. package/src/worksheet/appearance.ts +55 -0
  219. package/src/worksheet/axis.test.ts +185 -0
  220. package/src/worksheet/axis.ts +131 -0
  221. package/src/worksheet/background/read.ts +41 -0
  222. package/src/worksheet/background/roundtrip.test.ts +77 -0
  223. package/src/worksheet/background/write.ts +96 -0
  224. package/src/worksheet/cell-shift.ts +44 -0
  225. package/src/worksheet/cells.ts +75 -0
  226. package/src/worksheet/checkbox/formats.ts +53 -0
  227. package/src/worksheet/checkbox/ranges.ts +112 -0
  228. package/src/worksheet/checkbox/write.test.ts +62 -0
  229. package/src/worksheet/conditional/color-scale.ts +61 -0
  230. package/src/worksheet/conditional/data-bar.ts +76 -0
  231. package/src/worksheet/conditional/extensions.ts +95 -0
  232. package/src/worksheet/conditional/icon-reference.ts +69 -0
  233. package/src/worksheet/conditional/icon-set.test.ts +60 -0
  234. package/src/worksheet/conditional/icon-set.ts +79 -0
  235. package/src/worksheet/conditional/preview.ts +44 -0
  236. package/src/worksheet/conditional/read.ts +185 -0
  237. package/src/worksheet/conditional/text.test.ts +71 -0
  238. package/src/worksheet/conditional/text.ts +122 -0
  239. package/src/worksheet/conditional/threshold.ts +47 -0
  240. package/src/worksheet/conditional/types.ts +20 -0
  241. package/src/worksheet/conditional/write-bar.ts +66 -0
  242. package/src/worksheet/conditional/write.test.ts +218 -0
  243. package/src/worksheet/conditional/write.ts +103 -0
  244. package/src/worksheet/copied-axis.ts +70 -0
  245. package/src/worksheet/data/rows.ts +59 -0
  246. package/src/worksheet/data/source.test.ts +68 -0
  247. package/src/worksheet/data/source.ts +31 -0
  248. package/src/worksheet/data/types.ts +9 -0
  249. package/src/worksheet/data.test.ts +314 -0
  250. package/src/worksheet/dimensions/columns.ts +87 -0
  251. package/src/worksheet/dimensions/write.test.ts +110 -0
  252. package/src/worksheet/dimensions/write.ts +36 -0
  253. package/src/worksheet/filters/advanced.test.ts +57 -0
  254. package/src/worksheet/filters/color.ts +105 -0
  255. package/src/worksheet/filters/icon.test.ts +83 -0
  256. package/src/worksheet/filters/icon.ts +39 -0
  257. package/src/worksheet/filters/read.ts +114 -0
  258. package/src/worksheet/filters/relative-dates.ts +47 -0
  259. package/src/worksheet/filters/restore-icons.ts +33 -0
  260. package/src/worksheet/filters/restore.ts +169 -0
  261. package/src/worksheet/filters/rules.ts +23 -0
  262. package/src/worksheet/filters/types.ts +23 -0
  263. package/src/worksheet/filters/visibility.ts +188 -0
  264. package/src/worksheet/filters/write.ts +121 -0
  265. package/src/worksheet/formula/cache.ts +29 -0
  266. package/src/worksheet/formula/external-results.test.ts +39 -0
  267. package/src/worksheet/formula/functions.ts +29 -0
  268. package/src/worksheet/formula/prefix.ts +27 -0
  269. package/src/worksheet/formula/shared/read.test.ts +121 -0
  270. package/src/worksheet/formula/shared/read.ts +94 -0
  271. package/src/worksheet/formula/shared/references.ts +100 -0
  272. package/src/worksheet/formula/shared/types.ts +21 -0
  273. package/src/worksheet/formula/spill-read.ts +54 -0
  274. package/src/worksheet/formula/spill-write.ts +32 -0
  275. package/src/worksheet/formula/spill.test.ts +101 -0
  276. package/src/worksheet/formula/write.test.ts +26 -0
  277. package/src/worksheet/hyperlinks/location.ts +59 -0
  278. package/src/worksheet/hyperlinks/model.ts +22 -0
  279. package/src/worksheet/hyperlinks/read.ts +70 -0
  280. package/src/worksheet/hyperlinks/types.ts +21 -0
  281. package/src/worksheet/hyperlinks/write.test.ts +203 -0
  282. package/src/worksheet/hyperlinks/write.ts +51 -0
  283. package/src/worksheet/merge.test.ts +58 -0
  284. package/src/worksheet/merge.ts +61 -0
  285. package/src/worksheet/outline/columns.ts +46 -0
  286. package/src/worksheet/outline/metadata.ts +68 -0
  287. package/src/worksheet/outline/native.ts +81 -0
  288. package/src/worksheet/outline/read.ts +50 -0
  289. package/src/worksheet/outline/roundtrip.test.ts +73 -0
  290. package/src/worksheet/outline/types.ts +37 -0
  291. package/src/worksheet/outline/write.ts +110 -0
  292. package/src/worksheet/positions.test.ts +46 -0
  293. package/src/worksheet/positions.ts +48 -0
  294. package/src/worksheet/print/breaks.ts +72 -0
  295. package/src/worksheet/print/elements.ts +16 -0
  296. package/src/worksheet/print/page-text.ts +139 -0
  297. package/src/worksheet/print/setup.test.ts +141 -0
  298. package/src/worksheet/print/setup.ts +116 -0
  299. package/src/worksheet/progress/read.ts +73 -0
  300. package/src/worksheet/progress/solid.ts +26 -0
  301. package/src/worksheet/progress/types.ts +11 -0
  302. package/src/worksheet/progress/write.test.ts +63 -0
  303. package/src/worksheet/progress/write.ts +46 -0
  304. package/src/worksheet/read.ts +197 -0
  305. package/src/worksheet/rich-text.test.ts +41 -0
  306. package/src/worksheet/rich-text.ts +76 -0
  307. package/src/worksheet/sort/read.ts +115 -0
  308. package/src/worksheet/sort/relocate.ts +62 -0
  309. package/src/worksheet/sort/roundtrip.test.ts +116 -0
  310. package/src/worksheet/sort/types.ts +11 -0
  311. package/src/worksheet/sort/write.ts +77 -0
  312. package/src/worksheet/template.ts +9 -0
  313. package/src/worksheet/text.ts +33 -0
  314. package/src/worksheet/validation/extended.ts +36 -0
  315. package/src/worksheet/validation/image.ts +7 -0
  316. package/src/worksheet/validation/list-options/portable.ts +90 -0
  317. package/src/worksheet/validation/list-options/types.ts +14 -0
  318. package/src/worksheet/validation/list-options/wps.ts +51 -0
  319. package/src/worksheet/validation/read.ts +162 -0
  320. package/src/worksheet/validation/text.ts +13 -0
  321. package/src/worksheet/validation/write.test.ts +259 -0
  322. package/src/worksheet/validation/write.ts +99 -0
  323. package/src/worksheet/view/coordinates.ts +39 -0
  324. package/src/worksheet/view/named/read.ts +116 -0
  325. package/src/worksheet/view/named/roundtrip.test.ts +136 -0
  326. package/src/worksheet/view/named/sort.ts +57 -0
  327. package/src/worksheet/view/named/types.ts +15 -0
  328. package/src/worksheet/view/named/write.ts +107 -0
  329. package/src/worksheet/view/named/xml.ts +33 -0
  330. package/src/worksheet/view/panes.ts +75 -0
  331. package/src/worksheet/view/read.ts +61 -0
  332. package/src/worksheet/view/relocate.ts +57 -0
  333. package/src/worksheet/view/write.test.ts +91 -0
  334. package/src/worksheet/view/write.ts +57 -0
  335. package/src/worksheet/write.ts +86 -0
  336. package/README.md +0 -3
@@ -0,0 +1,64 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { formatWorkbookColumn, mapWorkbookNameReferences, parseWorkbookRange, workbookRows, type WorkbookDefinedName,
3
+ type WorkbookRange, type WorkbookWorksheetIdentity } from "@quirekit/workbook";
4
+ import { hasKnownAttributes } from "../../opc/shape";
5
+ import { children, readIndex, spreadNs } from "../../opc/xml";
6
+ import { isFilterDatabaseName } from "./filter";
7
+ import { isPrintName } from "./print";
8
+
9
+ /** @param node - Native name with a relative single-cell target. @param owner - Current sheet.
10
+ * @param anchor - First region's top-left offset from A1. @returns Mixed A1 reference in this sheet, if representable. */
11
+ function relativeName(node: Element, owner: WorkbookWorksheetIdentity, anchor: WorkbookRange): string | undefined {
12
+ if (node.namespaceURI !== spreadNs || children(node).length || !hasKnownAttributes(node, ["name", "localSheetId", "comment", "hidden"])) return;
13
+ const match = /^=?('(?:[^']|'')*'|[^'!\[\]:]+)!(\$?)([A-Z]{1,3})(\$?)([1-9]\d{0,6})$/iu.exec(node.textContent?.trim() ?? "");
14
+ if (!match) return;
15
+ const [, qualifier, columnLock, column, rowLock, row] = match;
16
+ const name = qualifier!.startsWith("'") ? qualifier!.slice(1, -1).replaceAll("''", "'") : qualifier!;
17
+ if (name.toUpperCase() !== owner.name.toUpperCase()) return;
18
+ const origin = parseWorkbookRange(owner.id, column! + row);
19
+ const targetRow = origin.startRow + (rowLock ? 0 : anchor.startRow);
20
+ const targetColumn = origin.startColumn + (columnLock ? 0 : anchor.startColumn);
21
+ if (targetRow >= workbookRows) return;
22
+ return columnLock + formatWorkbookColumn(targetColumn) + rowLock + (targetRow + 1);
23
+ }
24
+
25
+ /** @param nodes - Names from the original directory. @param directory - Sheet positions.
26
+ * @param known - Names already available in the calculation projection. @returns A resolver for preview-only source names. */
27
+ export function createXlsxConditionalNameResolver(nodes: readonly Element[], directory: readonly WorkbookWorksheetIdentity[],
28
+ known: readonly WorkbookDefinedName[]) {
29
+ const knownIds = new Set(known.map(({ id }) => id));
30
+ const sheetByName = new Map(directory.map(sheet => [sheet.name.toUpperCase(), sheet]));
31
+ const scopes = new Map<string | undefined, Map<string, Element | null>>();
32
+ const projected = new Set<Element>();
33
+ for (const [index, node] of nodes.entries()) {
34
+ if (isFilterDatabaseName(node) || isPrintName(node)) continue;
35
+ const scope = readIndex(node, "localSheetId");
36
+ const id = scope === undefined ? undefined : directory[scope]?.id;
37
+ const name = node.getAttribute("name")?.toUpperCase();
38
+ if (!name || node.hasAttribute("localSheetId") && !id) continue;
39
+ const entries = scopes.get(id) ?? new Map<string, Element | null>();
40
+ entries.set(name, entries.has(name) ? null : node);
41
+ scopes.set(id, entries);
42
+ if (knownIds.has("xlsx-defined-name-" + index)) projected.add(node);
43
+ }
44
+
45
+ /** @param formula - Native formula at the source anchor. @param owner - Owning worksheet.
46
+ * @param anchor - Original first region. @returns Executable predicate, or undefined for an unsupported name. */
47
+ return (formula: string, owner: WorkbookWorksheetIdentity, anchor: WorkbookRange): string | undefined => {
48
+ let supported = true;
49
+ const mapped = mapWorkbookNameReferences(formula, ref => {
50
+ const scope = ref.qualifier ? sheetByName.get(ref.qualifier.toUpperCase()) : owner;
51
+ const name = ref.name.toUpperCase();
52
+ const local = scope && scopes.get(scope.id)?.get(name);
53
+ const source = local === undefined && !ref.qualifier ? scopes.get(undefined)?.get(name) : local;
54
+ if (source === undefined || source && projected.has(source)) return;
55
+ if (source && local === source && scope?.id === owner.id) {
56
+ const converted = relativeName(source, owner, anchor);
57
+ if (converted) return converted;
58
+ }
59
+ supported = false;
60
+ return undefined;
61
+ });
62
+ return supported ? mapped : undefined;
63
+ };
64
+ }
@@ -0,0 +1,52 @@
1
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
2
+ import { expect, it } from "vitest";
3
+ import { openWorkbook, parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
4
+ import { createXlsx, openXlsx } from "../../index";
5
+
6
+ const workbookPart = "xl/workbook.xml";
7
+ const seed: WorkbookSnapshot = {
8
+ id: "names", version: 1, name: "设置", revision: 0, sheets: [
9
+ { id: "first", name: "汇总", cells: [] },
10
+ { id: "detail", name: "O'Brien", cells: [] }
11
+ ],
12
+ definedNames: [
13
+ { id: "user-range", name: "订单", target: { kind: "range", range: parseWorkbookRange("detail", "D2:D4") } },
14
+ { id: "label", name: "状态", scopeSheetId: "detail", target: { kind: "value", value: '已核"对' }, comment: "说明" }
15
+ ]
16
+ };
17
+
18
+ it("uses native range and scalar names, preserves source bytes, and rewrites scope indices on moves", async () => {
19
+ const bytes = createXlsx(seed);
20
+ const source = openXlsx("设置", bytes);
21
+ expect(source.restrictions).toEqual([]);
22
+ expect(source.write(source.snapshot)).toEqual(bytes);
23
+ expect(source.snapshot.definedNames).toMatchObject([
24
+ { name: "订单", target: { kind: "range", range: { sheetId: "2", startColumn: 3 } } },
25
+ { name: "状态", scopeSheetId: "2", target: { kind: "value", value: '已核"对' }, comment: "说明" }
26
+ ]);
27
+ const book = await openWorkbook(source.snapshot);
28
+ try {
29
+ const target = parseWorkbookRange("2", "A1");
30
+ const reviewed = book.prepare({ operationId: "move", baseRevision: 0, commands: [
31
+ { name: "moveWorksheet", target, params: { position: 1 } },
32
+ { name: "renameWorksheet", target, params: { name: "来源数据" } }
33
+ ] });
34
+ await book.commit(reviewed.id);
35
+ const changed = source.write(book.snapshot());
36
+ const xml = strFromU8(unzipSync(changed)[workbookPart]!);
37
+ expect(xml).toContain("name=\"状态\" localSheetId=\"0\"");
38
+ expect(xml).toContain("'来源数据'!$D$2:$D$4");
39
+ const reopened = openXlsx("重新打开", changed);
40
+ expect(reopened.restrictions).toEqual([]);
41
+ expect(reopened.snapshot.definedNames?.[1]?.scopeSheetId).toBe(reopened.snapshot.sheets[0]?.id);
42
+ } finally { await book.close(); }
43
+ });
44
+
45
+ it("retains unsupported dynamic names and their source archive", () => {
46
+ const parts = unzipSync(createXlsx(seed));
47
+ parts[workbookPart] = strToU8(strFromU8(parts[workbookPart]!).replace("'O''Brien'!$D$2:$D$4", "OFFSET('O''Brien'!$D$2,0,0,3,1)"));
48
+ const bytes = zipSync(parts);
49
+ const source = openXlsx("动态定义", bytes);
50
+ expect(source.restrictions).toContain("相对或动态定义名称");
51
+ expect(source.original()).toEqual(bytes);
52
+ });
@@ -0,0 +1,75 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { copyWorkbookDefinedNames, formatWorkbookNameTarget, formatWorkbookSpillReferences, parseWorkbookNameTarget,
3
+ type WorkbookDefinedName, type WorkbookWorksheetIdentity } from "@quirekit/workbook";
4
+ import { child, children, readIndex, spreadNs } from "../../opc/xml";
5
+ import { isWorksheetFilterName } from "./filter";
6
+ import { isPrintName } from "./print";
7
+
8
+ const attributes = new Set(["name", "localSheetId", "comment", "hidden"]);
9
+ const procedureFlags = new Set(["function", "vbProcedure"]);
10
+
11
+ /** @param element - One entry in the Workbook part. @returns Whether it belongs to the user catalog. */
12
+ function isUserName(element: Element): boolean { return !isPrintName(element) && !isWorksheetFilterName(element); }
13
+
14
+ /** @param nodes - Workbook-defined name elements. @param directory - Original worksheet positions.
15
+ * @param restrictions - Read-only diagnostics for retained features. @returns Supported user definitions. */
16
+ export function readWorkbookDefinedNames(nodes: readonly Element[], directory: readonly WorkbookWorksheetIdentity[],
17
+ restrictions: Set<string>): readonly WorkbookDefinedName[] {
18
+ const definitions: WorkbookDefinedName[] = [];
19
+ for (const [index, node] of nodes.entries()) {
20
+ if (!isUserName(node)) continue;
21
+ try {
22
+ // Calc may explicitly turn off procedure flags on an ordinary range name.
23
+ if (Array.from(node.attributes).some(attribute => !attributes.has(attribute.name)
24
+ && !(procedureFlags.has(attribute.name) && (attribute.value === "false" || attribute.value === "0"))) || children(node).length) {
25
+ throw new Error("Unknown defined-name metadata.");
26
+ }
27
+ const scopeIndex = readIndex(node, "localSheetId");
28
+ const scopeSheetId = scopeIndex !== undefined ? directory[scopeIndex]?.id : undefined;
29
+ if (node.hasAttribute("localSheetId") && !scopeSheetId) throw new Error("Unknown defined-name scope.");
30
+ const hidden = node.hasAttribute("hidden") ? node.getAttribute("hidden") : null;
31
+ if (hidden !== null && !["0", "1", "false", "true"].includes(hidden)) throw new Error("Unknown name visibility.");
32
+ const name = node.getAttribute("name") ?? "";
33
+ const target = parseWorkbookNameTarget(node.textContent ?? "", directory);
34
+ definitions.push({ id: "xlsx-defined-name-" + index, name, scopeSheetId, target, comment: node.getAttribute("comment") ?? undefined,
35
+ ...(hidden === "1" || hidden === "true" ? { hidden: true } : {}) });
36
+ } catch { restrictions.add("相对或动态定义名称"); }
37
+ }
38
+ try { return copyWorkbookDefinedNames(definitions, directory); }
39
+ catch {
40
+ restrictions.add("无效或重复的定义名称");
41
+ return [];
42
+ }
43
+ }
44
+
45
+ /** @param workbook - Native Workbook root. @returns Name container inserted in Workbook schema order. */
46
+ export function ensureXlsxDefinedNames(workbook: Element): Element {
47
+ const existing = child(workbook, "definedNames");
48
+ if (existing) return existing;
49
+ const created = workbook.ownerDocument!.createElementNS(spreadNs, "definedNames");
50
+ const preceding = child(workbook, "externalReferences") ?? child(workbook, "functionGroups") ?? child(workbook, "sheets")!;
51
+ workbook.insertBefore(created, preceding.nextSibling);
52
+ return created;
53
+ }
54
+
55
+ /** @param workbook - Workbook part. @param definitions - Currently committed names.
56
+ * @param directory - Final worksheet order and display names. */
57
+ export function writeWorkbookDefinedNames(workbook: Element, definitions: readonly WorkbookDefinedName[],
58
+ directory: readonly WorkbookWorksheetIdentity[]): void {
59
+ const checked = copyWorkbookDefinedNames(definitions, directory);
60
+ const names = checked.length ? ensureXlsxDefinedNames(workbook) : child(workbook, "definedNames");
61
+ if (!names) return;
62
+ for (const child of children(names, "definedName").filter(isUserName)) names.removeChild(child);
63
+ const sheets = new Map(directory.map((sheet, index) => [sheet.id, { name: sheet.name, index }]));
64
+ for (const definition of checked) {
65
+ const node = workbook.ownerDocument!.createElementNS(spreadNs, "definedName");
66
+ node.setAttribute("name", definition.name);
67
+ if (definition.scopeSheetId) node.setAttribute("localSheetId", String(sheets.get(definition.scopeSheetId)!.index));
68
+ if (definition.comment) node.setAttribute("comment", definition.comment);
69
+ if (definition.hidden) node.setAttribute("hidden", "1");
70
+ const expression = formatWorkbookNameTarget(definition.target, id => sheets.get(id)!.name).slice(1);
71
+ node.textContent = formatWorkbookSpillReferences(expression, "function").formula;
72
+ names.appendChild(node);
73
+ }
74
+ if (!children(names, "definedName").length) workbook.removeChild(names);
75
+ }
@@ -0,0 +1,68 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { formatWorkbookRange, parseWorkbookRange, type WorkbookSheet } from "@quirekit/workbook";
3
+ import { child, children, readIndex, spreadNs } from "../../opc/xml";
4
+ import { readPrintReferences } from "./print";
5
+
6
+ /** @param node - Workbook defined name. @returns Whether it declares the worksheet's native AutoFilter range. */
7
+ export function isFilterDatabaseName(node: Element): boolean {
8
+ return node.getAttribute("name")?.toUpperCase() === "_XLNM._FILTERDATABASE";
9
+ }
10
+
11
+ /** @param node - Workbook defined name. @returns Whether it identifies a worksheet filter range or its criteria. */
12
+ export function isWorksheetFilterName(node: Element): boolean {
13
+ return isFilterDatabaseName(node) || node.getAttribute("name")?.toUpperCase() === "_XLNM.CRITERIA";
14
+ }
15
+
16
+ /** @param names - Native filter database definitions. @param directory - Original worksheet directory and filters.
17
+ * @returns Whether each local name belongs to exactly one understood native range. */
18
+ export function validateFilterDatabaseNames(names: readonly Element[], directory: readonly WorkbookSheet[]): boolean {
19
+ const used = new Set<string>();
20
+ const valid = names.every(node => {
21
+ const index = readIndex(node, "localSheetId") ?? -1;
22
+ const owner = directory[index];
23
+ if (!owner?.autoFilter) return false;
24
+ const database = isFilterDatabaseName(node);
25
+ const key = `${index}:${database ? "list" : "criteria"}`;
26
+ const expected = database ? owner.autoFilter.range : owner.autoFilter.advanced?.criteria;
27
+ if (!expected || used.has(key)) return false;
28
+ const references = readPrintReferences(node, owner.name);
29
+ if (references?.length !== 1) return false;
30
+ try {
31
+ const range = parseWorkbookRange(owner.id, references[0]!);
32
+ used.add(key);
33
+ return formatWorkbookRange(range) === formatWorkbookRange(expected);
34
+ } catch { return false; }
35
+ });
36
+ return valid && directory.every(({ autoFilter }, index) => !autoFilter?.advanced || used.has(`${index}:list`)
37
+ && (!autoFilter.advanced.criteria || used.has(`${index}:criteria`)));
38
+ }
39
+
40
+ /** @param workbook - Native workbook root. @param directory - Current worksheet order, names, and filter ranges. */
41
+ export function writeFilterDatabaseNames(workbook: Element, directory: readonly WorkbookSheet[]): void {
42
+ let names = child(workbook, "definedNames");
43
+ if (names) {
44
+ for (const node of children(names, "definedName").filter(isWorksheetFilterName)) names.removeChild(node);
45
+ }
46
+ const document = workbook.ownerDocument!;
47
+ for (const [index, sheet] of directory.entries()) {
48
+ if (!sheet.autoFilter) continue;
49
+ if (!names) {
50
+ names = document.createElementNS(spreadNs, "definedNames");
51
+ const sheets = child(workbook, "sheets")!;
52
+ const external = child(workbook, "externalReferences");
53
+ workbook.insertBefore(names, (external ?? sheets).nextSibling);
54
+ }
55
+ const qualifier = "'" + sheet.name.replaceAll("'", "''") + "'!";
56
+ const { range, advanced } = sheet.autoFilter;
57
+ for (const [key, ref] of [["_xlnm._FilterDatabase", range], ["_xlnm.Criteria", advanced?.criteria]] as const) {
58
+ if (!ref) continue;
59
+ const definition = document.createElementNS(spreadNs, "definedName");
60
+ definition.setAttribute("name", key);
61
+ definition.setAttribute("localSheetId", String(index));
62
+ if (key === "_xlnm._FilterDatabase") definition.setAttribute("hidden", "1");
63
+ definition.textContent = qualifier + formatWorkbookRange(ref).replace(/([A-Z]+)([0-9]+)/gu, "$$$1$$$2");
64
+ names.appendChild(definition);
65
+ }
66
+ }
67
+ if (names && children(names, "definedName").length === 0) workbook.removeChild(names);
68
+ }
@@ -0,0 +1,62 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { formatWorkbookPrintArea, formatWorkbookPrintTitles, parseWorkbookPrintArea, parseWorkbookPrintTitles,
3
+ type WorkbookWorksheetPrintPatch, type WorkbookSheet } from "@quirekit/workbook";
4
+ import { child, children, readIndex, spreadNs } from "../../opc/xml";
5
+ import { ensureXlsxDefinedNames } from "./defined";
6
+ import { readPrintReferences } from "./print";
7
+
8
+ const areaName = "_xlnm.Print_Area";
9
+ const titleName = "_xlnm.Print_Titles";
10
+
11
+ /** @param definitions - Native names for one worksheet. @param sheet - Owning sheet name.
12
+ * @returns Workbook-relative print area and titles, or an error for unsupported name semantics. */
13
+ export function readXlsxPrintRanges(definitions: readonly Element[], sheet: string): WorkbookWorksheetPrintPatch {
14
+ const result: { -readonly [Field in keyof WorkbookWorksheetPrintPatch]: WorkbookWorksheetPrintPatch[Field] } = {};
15
+ const seen = new Set<string>();
16
+ for (const definition of definitions) {
17
+ const name = definition.getAttribute("name")!;
18
+ const references = readPrintReferences(definition, sheet);
19
+ if (!references || seen.has(name)) throw new Error("无法解析打印区域或标题。");
20
+ seen.add(name);
21
+ if (name === areaName) result.areas = references.map(parseWorkbookPrintArea);
22
+ else for (const reference of references) {
23
+ const row = /^\$\d/u.test(reference);
24
+ const key = row ? "titleRows" : "titleColumns";
25
+ if (result[key]) throw new Error("无法解析多段打印标题。");
26
+ result[key] = parseWorkbookPrintTitles(reference, row ? "row" : "column");
27
+ }
28
+ }
29
+ return result;
30
+ }
31
+
32
+ /** @param root - Workbook after its sheet directory is finalized. @param sheet - Committed sheet.
33
+ * @param index - Final worksheet index. @param previous - Retained state, including the source of a copy. */
34
+ export function writeXlsxPrintRanges(root: Element, sheet: WorkbookSheet, index: number, previous?: WorkbookSheet): void {
35
+ const old = previous?.view?.printLayout, next = sheet.view?.printLayout;
36
+ const qualifier = "'" + sheet.name.replaceAll("'", "''") + "'!";
37
+ /** @param layout - Saved settings before or after editing. @returns Absolute native title expressions. */
38
+ const titles = (layout: typeof next) => [
39
+ ...(layout?.titleRows ? [formatWorkbookPrintTitles(layout.titleRows, "row", true)] : []),
40
+ ...(layout?.titleColumns ? [formatWorkbookPrintTitles(layout.titleColumns, "column", true)] : [])
41
+ ];
42
+ const refs = [
43
+ [areaName, old?.areas.map(area => formatWorkbookPrintArea(area, true)) ?? [], next?.areas.map(area => formatWorkbookPrintArea(area, true)) ?? []],
44
+ [titleName, titles(old), titles(next)]
45
+ ] as const;
46
+ for (const [name, prior, ranges] of refs) {
47
+ if (prior.join(",") === ranges.join(",")) continue;
48
+ const names = ranges.length ? ensureXlsxDefinedNames(root) : child(root, "definedNames");
49
+ if (!names) continue;
50
+ const definition = children(names, "definedName").find(node => node.getAttribute("name") === name && readIndex(node, "localSheetId") === index);
51
+ if (ranges.length) {
52
+ const node = definition ?? root.ownerDocument!.createElementNS(spreadNs, "definedName");
53
+ node.setAttribute("name", name);
54
+ node.setAttribute("localSheetId", String(index));
55
+ node.textContent = ranges.map(range => qualifier + range).join(",");
56
+ if (!definition) names.appendChild(node);
57
+ } else if (definition) {
58
+ names.removeChild(definition);
59
+ if (!children(names, "definedName").length) root.removeChild(names);
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,62 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import type { WorkbookWorksheetIdentity } from "@quirekit/workbook";
3
+ import { child, children, readIndex } from "../../opc/xml";
4
+
5
+ const printName = /^_xlnm\.(Print_Area|Print_Titles)$/u;
6
+ const printReference = /^(?:'((?:[^']|'')+)'|([^'!,\s]+))!(\$[A-Z]{1,3}\$[1-9]\d*(?::\$[A-Z]{1,3}\$[1-9]\d*)?|\$[A-Z]{1,3}:\$[A-Z]{1,3}|\$[1-9]\d*:\$[1-9]\d*)(?=\s*(?:,|$))/iu;
7
+
8
+ /** @param definition - Native defined-name node. @returns Whether Excel reserves this name for printing. */
9
+ export function isPrintName(definition: Element): boolean {
10
+ return printName.test(definition.getAttribute("name") ?? "");
11
+ }
12
+
13
+ /**
14
+ * Parse only absolute references to the owning sheet. Quoted sheet names may contain commas.
15
+ * @param definition - Native print area or print titles.
16
+ * @param ownerName - Worksheet name at the original local index.
17
+ * @returns The range expressions suitable for requalifying, or undefined for unsupported definitions.
18
+ */
19
+ export function readPrintReferences(definition: Element, ownerName: string): string[] | undefined {
20
+ let remaining = (definition.textContent ?? "").trim();
21
+ const ranges: string[] = [];
22
+ for (;;) {
23
+ const match = printReference.exec(remaining);
24
+ if (!match || (match[1]?.replaceAll("''", "'") ?? match[2])?.toUpperCase() !== ownerName.toUpperCase()) return;
25
+ ranges.push(match[3]!);
26
+ remaining = remaining.slice(match[0].length).trimStart();
27
+ if (!remaining) return ranges;
28
+ remaining = remaining.slice(1).trimStart();
29
+ }
30
+ }
31
+
32
+ /** @param workbook - Native workbook part. @param before - Original worksheet order.
33
+ * @param after - Committed worksheet order. */
34
+ export function updatePrintNames(workbook: Element, before: readonly WorkbookWorksheetIdentity[], after: readonly WorkbookWorksheetIdentity[]): void {
35
+ const names = child(workbook, "definedNames");
36
+ if (!names) return;
37
+ const indices = new Map(after.map(({ id }, index) => [id, index]));
38
+ for (const definition of children(names, "definedName").filter(isPrintName)) {
39
+ const original = before[readIndex(definition, "localSheetId") ?? -1];
40
+ const references = original && readPrintReferences(definition, original.name);
41
+ if (!references) throw new Error("原文件的打印区域或打印标题无法随工作表安全调整。");
42
+ for (const [index, sheet] of after.entries()) {
43
+ if (sheet.origin?.sheetId !== original.id) continue;
44
+ const copy = definition.cloneNode(true) as Element;
45
+ writePrintName(copy, index, sheet.name, references);
46
+ names.appendChild(copy);
47
+ }
48
+ const index = indices.get(original.id);
49
+ if (index === undefined) names.removeChild(definition);
50
+ else writePrintName(definition, index, after[index]!.name, after[index]!.name !== original.name ? references : undefined);
51
+ }
52
+ if (!children(names, "definedName").length) workbook.removeChild(names);
53
+ }
54
+
55
+ /** @param definition - Native print definition. @param index - Worksheet position.
56
+ * @param name - Committed worksheet name. @param references - Optional absolute ranges to requalify. */
57
+ function writePrintName(definition: Element, index: number, name: string, references?: readonly string[]): void {
58
+ definition.setAttribute("localSheetId", String(index));
59
+ if (!references) return;
60
+ const qualifier = "'" + name.replaceAll("'", "''") + "'!";
61
+ definition.textContent = references.map(reference => qualifier + reference).join(",");
62
+ }
@@ -0,0 +1,46 @@
1
+ import type { WorkbookSnapshot } from "@quirekit/workbook";
2
+ import { strToU8 } from "fflate";
3
+ import { relationshipsPath } from "../opc/relationships";
4
+ import { child, contentTypeNs, packageRelationshipNs, parsePart, relationshipNs, rootOf, spreadNs } from "../opc/xml";
5
+ import { createXlsxWorksheetPart } from "../worksheet/template";
6
+ import type { XlsxPackage } from "./types";
7
+ import { updateXlsxWorkbookViews } from "./workbook-views";
8
+ import { writeXlsxWorksheetVisibility } from "./worksheets";
9
+
10
+ /**
11
+ * @param snapshot - New document.
12
+ * @returns Empty standard OPC parts ready for the common worksheet writer.
13
+ */
14
+ export function newXlsxPackage(snapshot: WorkbookSnapshot): XlsxPackage {
15
+ const workbookPath = "xl/workbook.xml";
16
+ const sheetPaths = new Map<string, string>();
17
+ const overrides: string[] = [`<Override PartName="/${workbookPath}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>`];
18
+ const relations: string[] = [];
19
+ const parts: Record<string, Uint8Array> = {};
20
+ const workbookXml = parsePart(strToU8(`<workbook xmlns="${spreadNs}" xmlns:r="${relationshipNs}"><workbookPr/><sheets/></workbook>`), workbookPath);
21
+ const workbook = rootOf(workbookXml, spreadNs, "workbook");
22
+ child(workbook, "workbookPr")!.setAttribute("date1904", snapshot.dateSystem === "1904" ? "1" : "0");
23
+ const sheets = child(workbook, "sheets")!;
24
+ snapshot.sheets.forEach((sheet, index) => {
25
+ const serial = index + 1;
26
+ const id = `rId${serial}`;
27
+ const target = `worksheets/sheet${serial}.xml`;
28
+ const path = `xl/${target}`;
29
+ sheetPaths.set(sheet.id, path);
30
+ const element = workbookXml.createElementNS(spreadNs, "sheet");
31
+ element.setAttribute("name", sheet.name);
32
+ element.setAttribute("sheetId", String(serial));
33
+ element.setAttributeNS(relationshipNs, "r:id", id);
34
+ writeXlsxWorksheetVisibility(element, sheet);
35
+ sheets.appendChild(element);
36
+ relations.push(`<Relationship Id="${id}" Type="${relationshipNs}/worksheet" Target="${target}"/>`);
37
+ overrides.push(`<Override PartName="/${path}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`);
38
+ parts[path] = createXlsxWorksheetPart();
39
+ });
40
+ updateXlsxWorkbookViews(workbook, snapshot.sheets, snapshot.sheets);
41
+ parts["[Content_Types].xml"] = strToU8(`<Types xmlns="${contentTypeNs}"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>${overrides.join("")}</Types>`);
42
+ parts["_rels/.rels"] = strToU8(`<Relationships xmlns="${packageRelationshipNs}"><Relationship Id="rId1" Type="${relationshipNs}/officeDocument" Target="${workbookPath}"/></Relationships>`);
43
+ const relPath = relationshipsPath(workbookPath);
44
+ parts[relPath] = strToU8(`<Relationships xmlns="${packageRelationshipNs}">${relations.join("")}</Relationships>`);
45
+ return { parts, workbookPath, workbookXml, sheetPaths, relationships: new Map() };
46
+ }
@@ -0,0 +1,46 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { relationshipOfType } from "../../opc/relationships";
3
+ import type { PackageRelationship } from "../../opc/types";
4
+ import { child, children, parsePart, rootOf, spreadNs } from "../../opc/xml";
5
+ import { readXlsxCheckboxStyles } from "../../styles/checkbox/bags";
6
+ import { readTheme, styleColorReader } from "../../styles/color";
7
+ import { readXlsxDifferentialPreviews } from "../../styles/differential-preview";
8
+ import { readWorkbookStyles } from "../../styles/read";
9
+ import { createXlsxTableStyleReader } from "../../table/styles/read";
10
+ import { readXlsxDifferentials } from "../../worksheet/conditional/read";
11
+ import { readXlsxTextCell } from "../../worksheet/rich-text";
12
+
13
+ /** @param parts - Source archive. @param relationships - Workbook relations owning presentation parts.
14
+ * @param restrictions - Diagnostics that require preserving original presentation.
15
+ * @returns Source strings, theme and styles shared by all worksheet readers. */
16
+ export function readXlsxAppearance(parts: Readonly<Record<string, Uint8Array>>, relationships: ReadonlyMap<string, PackageRelationship>,
17
+ restrictions: Set<string>) {
18
+ const sharedPath = relationshipOfType(relationships, "sharedStrings")?.path;
19
+ const themePath = relationshipOfType(relationships, "theme")?.path;
20
+ const themeRoot = readPresentationPart(parts, themePath, "theme", "http://schemas.openxmlformats.org/drawingml/2006/main", restrictions);
21
+ const theme = readTheme(themeRoot);
22
+ const stylePath = relationshipOfType(relationships, "styles")?.path;
23
+ const stylesheet = readPresentationPart(parts, stylePath, "styleSheet", spreadNs, restrictions);
24
+ const runColor = styleColorReader(stylesheet && child(stylesheet, "colors"), theme);
25
+ const strings = sharedPath ? children(rootOf(parsePart(parts[sharedPath], sharedPath), spreadNs, "sst"), "si")
26
+ .map(item => readXlsxTextCell(item, runColor)) : [];
27
+ const styles = readWorkbookStyles(stylesheet, theme);
28
+ const checkboxStyles = readXlsxCheckboxStyles(parts, relationships, stylesheet, restrictions);
29
+ const differentials = readXlsxDifferentials(stylesheet, theme);
30
+ const differentialPreviews = readXlsxDifferentialPreviews(stylesheet, runColor, differentials);
31
+ const tableStyles = createXlsxTableStyleReader(stylesheet, theme, runColor);
32
+ return { themeRoot, theme, runColor, strings, styles, checkboxStyles, differentials, differentialPreviews, tableStyles };
33
+ }
34
+
35
+ /** @param parts - Retained source archive. @param path - Optional related part. @param name - Expected root.
36
+ * @param namespace - Expected schema. @param restrictions - Read-only diagnostics.
37
+ * @returns Valid optional appearance part; malformed display data leaves readable cell contents available. */
38
+ function readPresentationPart(parts: Readonly<Record<string, Uint8Array>>, path: string | null | undefined, name: string, namespace: string,
39
+ restrictions: Set<string>): Element | undefined {
40
+ if (!path) return undefined;
41
+ try { return rootOf(parsePart(parts[path], path), namespace, name); }
42
+ catch {
43
+ restrictions.add("样式或主题部件无法读取");
44
+ return undefined;
45
+ }
46
+ }
@@ -0,0 +1,61 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { isWorkbookWorksheetVisible } from "@quirekit/workbook";
3
+ import type { PackageRelationship } from "../../opc/types";
4
+ import { child, children, readIndex, relationshipNs } from "../../opc/xml";
5
+ import { readPrintReferences } from "../names/print";
6
+ import type { XlsxWorksheetEntry, XlsxWorksheetPrintNames } from "./types";
7
+
8
+ /** @param workbook - SpreadsheetML workbook root. @param relationships - Native graph of sheet parts.
9
+ * @param restrictions - Workbook-wide preservation policy. @returns Worksheet IDs, parts and initial visible sheet. */
10
+ export function readXlsxWorksheetDirectory(workbook: Element, relationships: ReadonlyMap<string, PackageRelationship>, restrictions: Set<string>) {
11
+ const sheetPaths = new Map<string, string>();
12
+ const sheetList = child(workbook, "sheets");
13
+ if (!sheetList) throw new Error("XLSX 缺少工作表列表。");
14
+ const entries = children(sheetList, "sheet").map((entry): XlsxWorksheetEntry => {
15
+ const relationshipId = entry.getAttributeNS(relationshipNs, "id") ?? "";
16
+ const id = entry.getAttribute("sheetId") || relationshipId;
17
+ const name = entry.getAttribute("name") || "工作表";
18
+ const relation = relationships.get(relationshipId);
19
+ const path = relation?.path;
20
+ if (!path || !relation.type.endsWith("/worksheet")) throw new Error(`无法打开工作表 ${name}。此工作台支持常规工作表。`);
21
+ if (sheetPaths.has(id)) throw new Error("XLSX 包含重复的工作表标识。");
22
+ sheetPaths.set(id, path);
23
+ const state = entry.getAttribute("state");
24
+ if (state && state !== "visible" && state !== "hidden" && state !== "veryHidden") restrictions.add("未知的工作表可见性");
25
+ const visibility = state === "hidden" ? "hidden" : state && state !== "visible" ? "veryHidden" : undefined;
26
+ return { id, name, path, visibility };
27
+ });
28
+ const views = child(workbook, "bookViews");
29
+ const activeEntry = entries[readIndex(views && child(views, "workbookView"), "activeTab") ?? 0];
30
+ const initialWorksheetId = (activeEntry && isWorkbookWorksheetVisible(activeEntry) ? activeEntry : entries.find(isWorkbookWorksheetVisible))?.id;
31
+ if (!initialWorksheetId) throw new Error("XLSX 未包含可见的工作表。");
32
+ return { entries, sheetPaths, initialWorksheetId };
33
+ }
34
+
35
+ /** @param printNames - Native scoped print areas and titles. @param entries - Worksheets in source order.
36
+ * @param relationships - Workbook-level references whose targets must have unambiguous ownership.
37
+ * @param worksheetRestrictions - Diagnostics restricting directory edits.
38
+ * @returns Print definitions indexed by their original sheet ordinal. */
39
+ export function readXlsxWorksheetPrintNames(printNames: readonly Element[], entries: readonly XlsxWorksheetEntry[],
40
+ relationships: ReadonlyMap<string, PackageRelationship>, worksheetRestrictions: Set<string>): XlsxWorksheetPrintNames {
41
+ const printBySheet = new Map<number, Element[]>();
42
+ for (const node of printNames) {
43
+ const index = readIndex(node, "localSheetId") ?? -1;
44
+ const group = printBySheet.get(index);
45
+ if (group) group.push(node);
46
+ else printBySheet.set(index, [node]);
47
+ }
48
+ const unknownPrintOwner = [...printBySheet.keys()].some(index => index < 0 || index >= entries.length);
49
+ if (unknownPrintOwner || printNames.some(node => {
50
+ const owner = entries[readIndex(node, "localSheetId") ?? -1];
51
+ return !owner || !readPrintReferences(node, owner.name);
52
+ })) worksheetRestrictions.add("无法定位的打印区域或打印标题");
53
+ const partUses = new Set<string>();
54
+ for (const relation of relationships.values()) {
55
+ const target = relation.path?.toLowerCase();
56
+ if (!target) continue;
57
+ if (partUses.has(target)) worksheetRestrictions.add("多个关系共用同一工作簿部件");
58
+ partUses.add(target);
59
+ }
60
+ return { printBySheet, unknownPrintOwner };
61
+ }
@@ -0,0 +1,27 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { commentRoles } from "../../comments/xml";
3
+ import type { PackageRelationship } from "../../opc/types";
4
+ import { child, children } from "../../opc/xml";
5
+ import { pivotRoles } from "../../pivot/xml";
6
+ import { featurePropertyRelationship } from "../../styles/checkbox/bags";
7
+ import { hasKnownWorkbookExtensions } from "../extensions";
8
+
9
+ /** @param parts - Source ZIP entries. @param workbook - Workbook part. @param relationships - Native relationship directory.
10
+ * @param imageRoles - Relationships recognized by the image reader. @param externalRelationshipIds - Supported external cache relationships.
11
+ * @param arrayMetadataRelationshipId - Recognized array metadata relation.
12
+ * @param restrictions - Reasons for original-only access. @param worksheetRestrictions - Separate sheet directory limitations. */
13
+ export function noteXlsxWorkbookRestrictions(parts: Readonly<Record<string, Uint8Array>>, workbook: Element,
14
+ relationships: ReadonlyMap<string, PackageRelationship>, imageRoles: ReadonlySet<string>, externalRelationshipIds: ReadonlySet<string> | undefined,
15
+ arrayMetadataRelationshipId: string | undefined, restrictions: Set<string>, worksheetRestrictions: Set<string>): void {
16
+ if (Object.keys(parts).some(path => /vbaProject|^_xmlsignatures\//iu.test(path))) restrictions.add("宏或数字签名");
17
+ for (const relation of relationships.values()) {
18
+ if (imageRoles.has(relation.id) || externalRelationshipIds?.has(relation.id) || relation.type === pivotRoles.cache || relation.type === commentRoles.people) continue;
19
+ if (relation.type !== featurePropertyRelationship && !/\/(worksheet|sharedStrings|styles|theme|calcChain|sheetMetadata)$/u.test(relation.type)) restrictions.add("专用工作簿部件");
20
+ if (relation.type.endsWith("/sheetMetadata") && arrayMetadataRelationshipId !== relation.id) restrictions.add("动态数组元数据");
21
+ }
22
+ const protection = child(workbook, "workbookProtection");
23
+ // Some producers serialize an empty placeholder even when the workbook is unlocked.
24
+ if (protection && (protection.hasAttributes() || children(protection).length)) restrictions.add("工作簿保护");
25
+ if (!hasKnownWorkbookExtensions(workbook)) restrictions.add("工作簿扩展");
26
+ if (child(workbook, "customWorkbookViews")) worksheetRestrictions.add("自定义工作簿视图");
27
+ }
@@ -0,0 +1,48 @@
1
+ import { openWorkbook, parseWorkbookRange } from "@quirekit/workbook";
2
+ import { expect, it } from "vitest";
3
+ import { createXlsx, openXlsx } from "../../index";
4
+
5
+ const source = createXlsx({ version: 1, revision: 0, id: "book", name: "Workbook", sheets: [
6
+ { id: "sheet", name: "Sheet", cells: [
7
+ { row: 0, column: 0, input: { kind: "value", value: "订单", textRuns: [{ start: 0, end: 2, style: { bold: true } }] } },
8
+ { row: 0, column: 1, input: { kind: "formula", formula: "=LEN(A1)" } },
9
+ { row: 1, column: 0, input: { kind: "value", value: 17 } }
10
+ ] }
11
+ ] });
12
+
13
+ it("shares only immutable cells with the write baseline and keeps the default import detached", async () => {
14
+ const shared = openXlsx("Shared", source, { shareCellInputs: true });
15
+ const detached = openXlsx("Detached", source);
16
+ const sheet = shared.snapshot.sheets[0]!;
17
+ const original = sheet.cells[0]!;
18
+ const input = original.input;
19
+ expect(sheet.cells).toEqual(detached.snapshot.sheets[0]!.cells);
20
+ expect(input.kind).toBe("value");
21
+ if (input.kind !== "value" || !input.textRuns?.length) throw new Error("The fixture must contain rich text.");
22
+
23
+ expect(Reflect.set(sheet.cells, "0", sheet.cells[1])).toBe(false);
24
+ expect(Reflect.set(original, "column", 2)).toBe(false);
25
+ expect(Reflect.set(input, "value", "假订单")).toBe(false);
26
+ expect(Reflect.set(input.textRuns, "0", {})).toBe(false);
27
+ expect(Reflect.set(input.textRuns[0]!, "end", 1)).toBe(false);
28
+ expect(Reflect.set(input.textRuns[0]!.style, "bold", false)).toBe(false);
29
+ expect(shared.write(shared.snapshot)).toEqual(source);
30
+
31
+ const detachedCell = detached.snapshot.sheets[0]!.cells[2]!;
32
+ expect(Reflect.set(detachedCell.input, "value", 23)).toBe(true);
33
+ const written = openXlsx("Edited", detached.write(detached.snapshot));
34
+ expect(written.snapshot.sheets[0]!.cells[2]!.input).toEqual({ kind: "value", value: 23 });
35
+
36
+ const workbook = await openWorkbook(shared.snapshot);
37
+ try {
38
+ const candidate = workbook.prepare({ operationId: "edit-detached-from-import", baseRevision: 0, commands: [
39
+ { name: "setCells", target: parseWorkbookRange(sheet.id, "A2"), params: { value: 25 } }
40
+ ] });
41
+ await workbook.commit(candidate.id);
42
+ expect(sheet.cells[2]!.input).toEqual({ kind: "value", value: 17 });
43
+ const reopened = openXlsx("Edited session", shared.write(workbook.snapshot()));
44
+ expect(reopened.snapshot.sheets[0]!.cells[2]!.input).toEqual({ kind: "value", value: 25 });
45
+ await workbook.undo("undo-detached-edit");
46
+ expect(shared.write(workbook.snapshot())).toEqual(source);
47
+ } finally { await workbook.close(); }
48
+ });