@dztabel/excel-kit 0.0.0-stage → 0.9.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 (94) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/DISTRIBUTION.md +13 -0
  3. package/LICENSE +45 -0
  4. package/README.md +74 -2
  5. package/SKILL.md +101 -0
  6. package/THIRD-PARTY-NOTICES.txt +3050 -0
  7. package/VALIDATION.md +39 -0
  8. package/bin/excel-kit.cjs +50 -0
  9. package/package.json +19 -4
  10. package/recipes/README.md +29 -0
  11. package/recipes/audit-and-repair/README.md +30 -0
  12. package/recipes/audit-and-repair/inspect.json +7 -0
  13. package/recipes/audit-and-repair/recipe.js +48 -0
  14. package/recipes/audit-and-repair/request.json +22 -0
  15. package/recipes/audit-and-repair/sample/clean-control.xlsx +0 -0
  16. package/recipes/audit-and-repair/sample/expected.json +15 -0
  17. package/recipes/audit-and-repair/sample/model-to-check.xlsx +0 -0
  18. package/recipes/edit-protected-workbook/README.md +30 -0
  19. package/recipes/edit-protected-workbook/prepare.json +10 -0
  20. package/recipes/edit-protected-workbook/recipe.js +41 -0
  21. package/recipes/edit-protected-workbook/request.json +14 -0
  22. package/recipes/fill-template/README.md +30 -0
  23. package/recipes/fill-template/recipe.js +46 -0
  24. package/recipes/fill-template/request.json +18 -0
  25. package/recipes/fill-template/sample/derive-template.request.json +22 -0
  26. package/recipes/fill-template/sample/original/LICENSE +201 -0
  27. package/recipes/fill-template/sample/original/cf-hyperlink-image-protection.xlsx +0 -0
  28. package/recipes/fill-template/sample/template.xlsx +0 -0
  29. package/recipes/import-clean-append/README.md +30 -0
  30. package/recipes/import-clean-append/prepare.json +8 -0
  31. package/recipes/import-clean-append/recipe.js +77 -0
  32. package/recipes/import-clean-append/request.json +22 -0
  33. package/recipes/import-clean-append/sample/incoming-1.csv +4 -0
  34. package/recipes/import-clean-append/sample/incoming-2.csv +3 -0
  35. package/recipes/import-clean-append/sample/trading-table.xlsx +0 -0
  36. package/recipes/inventory-media/README.md +31 -0
  37. package/recipes/inventory-media/prepare.json +9 -0
  38. package/recipes/inventory-media/recipe.js +44 -0
  39. package/recipes/inventory-media/request.json +7 -0
  40. package/recipes/inventory-media/sample/LICENSE +268 -0
  41. package/recipes/inventory-media/sample/NOTICE +36 -0
  42. package/recipes/inventory-media/sample/WithEmbeded.xlsx +0 -0
  43. package/recipes/inventory-media/sample/blue.png +0 -0
  44. package/recipes/inventory-media/sample/green.jpg +0 -0
  45. package/recipes/normalize-codes/README.md +30 -0
  46. package/recipes/normalize-codes/prepare.json +73 -0
  47. package/recipes/normalize-codes/recipe.js +34 -0
  48. package/recipes/normalize-codes/request.json +7 -0
  49. package/recipes/normalize-codes/sample/trading-table.xlsx +0 -0
  50. package/recipes/pivot-by-slicer/README.md +30 -0
  51. package/recipes/pivot-by-slicer/prepare.json +11 -0
  52. package/recipes/pivot-by-slicer/recipe.js +34 -0
  53. package/recipes/pivot-by-slicer/request.json +14 -0
  54. package/recipes/roll-forward-period/README.md +30 -0
  55. package/recipes/roll-forward-period/prepare.json +10 -0
  56. package/recipes/roll-forward-period/recipe.js +49 -0
  57. package/recipes/roll-forward-period/request.json +13 -0
  58. package/recipes/roll-forward-period/sample/budget-template.xlsx +0 -0
  59. package/recipes/style-matching-sheets/README.md +28 -0
  60. package/recipes/style-matching-sheets/recipe.js +38 -0
  61. package/recipes/style-matching-sheets/request.json +17 -0
  62. package/recipes/style-matching-sheets/sample/build-workbook.request.json +13 -0
  63. package/recipes/style-matching-sheets/sample/report-tables.xlsx +0 -0
  64. package/recipes/update-assumptions/README.md +29 -0
  65. package/recipes/update-assumptions/recipe.js +66 -0
  66. package/recipes/update-assumptions/request.json +10 -0
  67. package/recipes/update-assumptions/sample/build-model.request.json +12 -0
  68. package/recipes/update-assumptions/sample/cost-model.xlsx +0 -0
  69. package/recipes/update-matching-records/README.md +35 -0
  70. package/recipes/update-matching-records/incomplete-strict.json +33 -0
  71. package/recipes/update-matching-records/incomplete.json +32 -0
  72. package/recipes/update-matching-records/prepare-incomplete.json +21 -0
  73. package/recipes/update-matching-records/recipe.js +35 -0
  74. package/recipes/update-matching-records/request.json +29 -0
  75. package/recipes/update-matching-records/sample/trading-table.xlsx +0 -0
  76. package/reference/api.md +59 -0
  77. package/reference/audit.md +50 -0
  78. package/reference/calculation.md +82 -0
  79. package/reference/cost.md +61 -0
  80. package/reference/deliverable.md +66 -0
  81. package/reference/editing-and-saving.md +69 -0
  82. package/reference/errors.md +67 -0
  83. package/reference/external-links.md +35 -0
  84. package/reference/function-limits.md +30 -0
  85. package/reference/paging.md +59 -0
  86. package/reference/pivots.md +40 -0
  87. package/reference/protection.md +63 -0
  88. package/reference/reading.md +70 -0
  89. package/reference/scripts.md +74 -0
  90. package/reference/selection.md +43 -0
  91. package/reference/session-loop.md +62 -0
  92. package/reference/sessions.md +48 -0
  93. package/reference/unsupported.md +31 -0
  94. package/release.json +41 -0
@@ -0,0 +1,13 @@
1
+ {
2
+ "input": "sample/budget-with-objects.xlsx",
3
+ "output": "budget-2026-02.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "source": "2026 01",
8
+ "target": "2026 02",
9
+ "updates": [{ "cell": "B4", "value": 5 }, { "cell": "B5", "value": 1 }, { "cell": "B6", "value": 10 }],
10
+ "assumptions": [{ "sheet": "假设", "cell": "B2", "value": 0.1 }],
11
+ "summary": { "sheet": "汇总", "range": "A4", "values": [["2026-02", { "formula": "=SUM('2026 02'!D4:D6)" }]] }
12
+ }
13
+ }
@@ -0,0 +1,28 @@
1
+ # 对名称匹配的工作表批量设置格式、打印与视图
2
+
3
+ 对名称匹配正则表达式的每张工作表应用同一组格式、冻结窗格、打印设置与视图,每张表一步,并报告处理了哪些表、没动哪些表。
4
+
5
+ ## 运行
6
+
7
+ 在本目录下依次执行:
8
+
9
+ 1. `excel-kit script request.json`:生成 `report-tables-styled.xlsx`。
10
+
11
+ `request.json` 里的路径相对本目录。脚本本体是 `recipe.js`,开头的注释列出了全部参数。
12
+
13
+ ## 参数
14
+
15
+ `pattern` 是表名的正则;`format`、`freeze`、`print`、`view` 是要应用的设置;`expectSheets` 是应当匹配的表数,用来防止正则写错。
16
+
17
+ ## 样本与许可
18
+
19
+ `sample/report-tables.xlsx` 是用公开操作合成的 7 张表的工作簿,不依据任何真实文件,建造请求是 `sample/build-workbook.request.json`。仓库内的测试另用用户提供的 30 张表的真实工程表做了一个额外用例,该文件不随包发布。
20
+
21
+ ## 样本上的结果
22
+
23
+ `^表2\.\d+ ` 匹配 3 张表:表头加粗反白、金额列两位小数、冻结首行、A4 横向并重复首行、缩放 90% 且不显示网格线;其余 4 张表不变,跨表合计仍为 811.5。
24
+
25
+ ## 要点
26
+
27
+ - 格式类步骤不改变数值,用 `calculation:{mode:"none"}` 省去计算。
28
+ - 任一张表设置失败(例如受保护)则整体失败:只设置了一半的报表不如不设置。
@@ -0,0 +1,38 @@
1
+ // Apply the same formatting, print settings and view to every worksheet whose
2
+ // name matches a pattern, one sheet per step, and report what was done to
3
+ // which sheet. Sheets that do not match are not touched.
4
+ //
5
+ // args: { pattern, format?, print?, view?, freeze?, expectSheets? }
6
+ // pattern ECMAScript regular expression tested against each sheet name
7
+ // format [{ range, style }] applied on every matching sheet
8
+ // print print.set properties
9
+ // view sheet.view settings
10
+ // freeze { rows, columns }
11
+ // expectSheets number of sheets that must match, as a guard against a wrong pattern
12
+ const must = (response, what) => {
13
+ if (!response.ok) {
14
+ const first = response.calculation?.diagnostics?.[0];
15
+ throw new Error(response.error ? `${what}: ${response.error.code} ${response.error.message}` : `${what}: CALCULATION_INCOMPLETE calculation ${response.calculation?.status}${first ? ` (${first.code} at ${first.sheet}!${first.cell}: ${first.message})` : ''}`);
16
+ }
17
+ return response;
18
+ };
19
+ const pattern = new RegExp(args.pattern, 'u');
20
+ const sheets = must(await wb.inspect(), 'Inspect sheets').workbook.sheets;
21
+ const matching = sheets.filter(sheet => pattern.test(sheet.name));
22
+ if (args.expectSheets !== undefined && matching.length !== args.expectSheets) throw new Error(`Pattern matched ${matching.length} sheets (${matching.map(sheet => sheet.name).join(', ') || 'none'}), expected ${args.expectSheets}.`);
23
+
24
+ const applied = [];
25
+ for (const { name: sheet } of matching) {
26
+ const operations = [
27
+ ...(args.format ?? []).map(item => ({ op: 'format', sheet, range: item.range, style: item.style })),
28
+ ...(args.freeze ? [{ op: 'layout', sheet, freeze: args.freeze }] : []),
29
+ ...(args.print ? [{ op: 'print.set', sheet, ...args.print }] : []),
30
+ ...(args.view ? [{ op: 'sheet.view', sheet, settings: args.view }] : []),
31
+ ];
32
+ // Formatting does not change any value, so no calculation is needed for these steps.
33
+ const step = await wb.run({ id: sheet, operations, calculation: { mode: 'none' } });
34
+ // One sheet that cannot take the settings (for example a protected one) makes the whole job fail: a half-styled report is worse than none.
35
+ if (!step.ok) throw new Error(`${sheet}: ${step.error.code} ${step.error.message}`);
36
+ applied.push({ sheet, operations: operations.length });
37
+ }
38
+ return { matched: matching.map(sheet => sheet.name), untouched: sheets.filter(sheet => !pattern.test(sheet.name)).map(sheet => sheet.name), applied };
@@ -0,0 +1,17 @@
1
+ {
2
+ "input": "sample/report-tables.xlsx",
3
+ "output": "report-tables-styled.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "pattern": "^表2\\.\\d+ ",
8
+ "expectSheets": 3,
9
+ "format": [
10
+ { "range": "A1:C1", "style": { "font": { "bold": true, "color": "FFFFFF" }, "fill": "1F4E78", "alignment": { "horizontal": "center" } } },
11
+ { "range": "C2:C200", "style": { "numberFormat": "#,##0.00" } }
12
+ ],
13
+ "freeze": { "rows": 1, "columns": 0 },
14
+ "print": { "orientation": "landscape", "paperSize": 9, "titles": { "rows": { "start": 1, "count": 1 } }, "scaling": { "mode": "fit", "width": 1, "height": 0 }, "headerFooter": { "oddHeader": "&C&A", "oddFooter": "&R第 &P 页" } },
15
+ "view": { "zoomScale": 90, "showGridLines": false }
16
+ }
17
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "create": { "sheets": ["目录", "表1 总览", "表2.1 设计费", "表2.2 监理费", "表2.3 咨询费", "附表A 取费标准", "说明"] },
3
+ "output": "sample/report-tables.xlsx",
4
+ "operations": [
5
+ { "op": "write", "sheet": "目录", "range": "A1", "values": [["表号", "名称"], ["表1", "总览"], ["表2.1", "设计费"], ["表2.2", "监理费"], ["表2.3", "咨询费"]] },
6
+ { "op": "write", "sheet": "表1 总览", "range": "A1", "values": [["序号", "费用名称", "金额"], [1, "设计费", { "formula": "='表2.1 设计费'!C4" }], [2, "监理费", { "formula": "='表2.2 监理费'!C4" }], [3, "咨询费", { "formula": "='表2.3 咨询费'!C4" }], [null, "合计", { "formula": "=SUM(C2:C4)" }]] },
7
+ { "op": "write", "sheet": "表2.1 设计费", "range": "A1", "values": [["序号", "项目", "金额"], [1, "方案设计", 120], [2, "施工图设计", 380], [null, "合计", { "formula": "=SUM(C2:C3)" }]] },
8
+ { "op": "write", "sheet": "表2.2 监理费", "range": "A1", "values": [["序号", "项目", "金额"], [1, "施工监理", 210], [2, "保修期监理", 15], [null, "合计", { "formula": "=SUM(C2:C3)" }]] },
9
+ { "op": "write", "sheet": "表2.3 咨询费", "range": "A1", "values": [["序号", "项目", "金额"], [1, "造价咨询", 64], [2, "招标代理", 22.5], [null, "合计", { "formula": "=SUM(C2:C3)" }]] },
10
+ { "op": "write", "sheet": "附表A 取费标准", "range": "A1", "values": [["档位", "费率"], ["100以下", 0.015], ["100-500", 0.011]] },
11
+ { "op": "write", "sheet": "说明", "range": "A1", "values": [["本工作簿为合成样本,不依据任何真实文件生成。"]] }
12
+ ]
13
+ }
@@ -0,0 +1,29 @@
1
+ # 只改指定假设并返回结果的完整上游
2
+
3
+ 确认每个要改的假设确实是所求结果上游的输入单元格,只改这些单元格,只重算所求结果,并返回每个结果的上游公式、链条末端的输入单元格及其取值,以及修改前后的工作簿版本。
4
+
5
+ ## 运行
6
+
7
+ 在本目录下依次执行:
8
+
9
+ 1. `excel-kit script request.json`:生成 `cost-model-updated.xlsx`。
10
+
11
+ `request.json` 里的路径相对本目录。脚本本体是 `recipe.js`,开头的注释列出了全部参数。
12
+
13
+ ## 参数
14
+
15
+ `assumptions` 是要改的输入;`results` 是要重算并解释的结果单元格。
16
+
17
+ ## 样本与许可
18
+
19
+ `sample/cost-model.xlsx` 是用公开操作合成的小型造价模型,不依据任何真实文件,建造请求是 `sample/build-model.request.json`。仓库内的测试另用用户提供的真实工程表做了一个额外用例,该文件没有再分发许可,不随包发布。
20
+
21
+ ## 样本上的结果
22
+
23
+ 设计费率由 3% 改为 3.5%:总投资 59,251,500 → 59,535,000,单方指标 4,937.625 → 4,961.25;两个结果的上游输入都是假设表的 5 个单元格。
24
+
25
+ ## 要点
26
+
27
+ - 不在任何所求结果上游的"假设"、或者本身是公式的单元格,在改动之前就被拒绝。
28
+ - 只按目标重算,未涉及的公式缓存按产品规则失效,不会冒充本次结果。
29
+ - 上游按公式里写明的静态引用追溯。`INDIRECT`、`OFFSET` 这类在运行时才决定的来源不在其中;依赖查询会在 `limitations` 里用 `RUNTIME_REFERENCES_PENDING` 指出这样的公式。
@@ -0,0 +1,66 @@
1
+ // Change only the stated assumptions, recalculate only the stated results,
2
+ // and return each result with everything it depends on: the formulas in its
3
+ // chain, the input cells at the ends of the chain with their values, and the
4
+ // workbook versions before and after. Refuses an "assumption" that none of
5
+ // the results depends on, and refuses to overwrite a formula.
6
+ //
7
+ // args: { assumptions, results }
8
+ // assumptions [{ sheet, cell, value }] inputs to change
9
+ // results [{ sheet, cell }] results to recalculate and explain
10
+ const must = (response, what) => {
11
+ if (!response.ok) {
12
+ const first = response.calculation?.diagnostics?.[0];
13
+ throw new Error(response.error ? `${what}: ${response.error.code} ${response.error.message}` : `${what}: CALCULATION_INCOMPLETE calculation ${response.calculation?.status}${first ? ` (${first.code} at ${first.sheet}!${first.cell}: ${first.message})` : ''}`);
14
+ }
15
+ return response;
16
+ };
17
+ const at = item => `${item.sheet}!${item.cell}`;
18
+ const targets = args.results.map(item => ({ sheet: item.sheet, range: item.cell }));
19
+ const resultValues = async () => must(await wb.read({ ranges: targets, calculation: { mode: 'targets', targets } }), 'Read results').ranges.map(range => range.cells[0][0]);
20
+
21
+ // The static dependency chain of every result, all the way up.
22
+ const chains = must(await wb.query({ dependencies: args.results.map(item => ({ ...item, direction: 'precedents', transitive: true, limit: 1000 })) }), 'Read dependencies').dependencies;
23
+ for (const chain of chains) if (chain.nextOffset !== null) throw new Error(`${at(chain)} has more than 1,000 upstream ranges; narrow the request.`);
24
+ const upstreamOf = chains.map(chain => [...new Set(chain.items.map(item => `${item.sheet}!${item.range}`))]);
25
+
26
+ // Read every upstream range once to tell formulas from inputs.
27
+ const ranges = [...new Set(upstreamOf.flat())].map(text => { const split = text.lastIndexOf('!'); return { sheet: text.slice(0, split), range: text.slice(split + 1) }; });
28
+ const upstreamCells = new Map();
29
+ if (ranges.length) for (const range of must(await wb.read({ ranges }), 'Read upstream').ranges) for (const row of range.cells) for (const cell of row) upstreamCells.set(`${range.sheet}!${cell.address}`, cell);
30
+
31
+ for (const assumption of args.assumptions) {
32
+ const cell = upstreamCells.get(at(assumption));
33
+ if (!cell) throw new Error(`${at(assumption)} is not upstream of any requested result; changing it cannot affect them.`);
34
+ if (cell.kind === 'formula') throw new Error(`${at(assumption)} holds a formula (${cell.formula}); an assumption must be an input cell.`);
35
+ }
36
+
37
+ const before = await resultValues(), inputVersion = wb.version;
38
+ const step = await wb.run({ operations: args.assumptions.map(item => ({ op: 'write', sheet: item.sheet, range: item.cell, values: [[item.value]] })), calculation: { mode: 'targets', targets }, read: targets });
39
+ must(step, 'Update failed');
40
+ if (step.result.changes.cells !== args.assumptions.length) throw new Error(`Expected to change ${args.assumptions.length} cells, changed ${step.result.changes.cells}.`);
41
+ const after = step.result.ranges.map(range => range.cells[0][0]);
42
+
43
+ const changed = new Map(args.assumptions.map(item => [at(item), item.value]));
44
+ return {
45
+ inputVersion, outputVersion: wb.version, changedCells: step.result.changes.cells,
46
+ results: args.results.map((item, index) => {
47
+ const cells = [...upstreamCells.entries()].filter(([address]) => belongs(address, upstreamOf[index]));
48
+ return {
49
+ sheet: item.sheet, cell: item.cell, formula: after[index].formula, before: before[index].result?.value ?? null, after: after[index].result?.value ?? null,
50
+ upstreamFormulas: cells.filter(([, cell]) => cell.kind === 'formula').map(([address, cell]) => ({ cell: address, formula: cell.formula })),
51
+ upstreamInputs: cells.filter(([, cell]) => cell.kind !== 'formula' && cell.result !== null && cell.result.type !== 'blank').map(([address, cell]) => ({ cell: address, value: changed.has(address) ? changed.get(address) : cell.result.value, changed: changed.has(address) })),
52
+ };
53
+ }),
54
+ };
55
+
56
+ // Whether a cell address lies inside one of the upstream ranges of this result.
57
+ function belongs(address, list) {
58
+ const split = address.lastIndexOf('!'), sheet = address.slice(0, split), cell = address.slice(split + 1);
59
+ const point = text => { const match = /^\$?([A-Z]+)\$?(\d+)$/.exec(text); return { column: [...match[1]].reduce((n, c) => n * 26 + c.charCodeAt(0) - 64, 0), row: Number(match[2]) }; };
60
+ const here = point(cell);
61
+ return list.some(text => {
62
+ const cut = text.lastIndexOf('!'); if (text.slice(0, cut) !== sheet) return false;
63
+ const [from, to = from] = text.slice(cut + 1).split(':').map(point);
64
+ return here.row >= from.row && here.row <= to.row && here.column >= from.column && here.column <= to.column;
65
+ });
66
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "input": "sample/cost-model.xlsx",
3
+ "output": "cost-model-updated.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "assumptions": [{ "sheet": "假设", "cell": "B4", "value": 0.035 }],
8
+ "results": [{ "sheet": "汇总", "cell": "B2" }, { "sheet": "汇总", "cell": "B3" }]
9
+ }
10
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "create": { "sheets": ["假设", "计算", "汇总"] },
3
+ "output": "sample/cost-model.xlsx",
4
+ "operations": [
5
+ { "op": "write", "sheet": "假设", "range": "A1", "values": [["参数", "取值", "单位"], ["建筑面积", 12000, "平方米"], ["单方造价", 4500, "元/平方米"], ["设计费率", 0.03, null], ["监理费率", 0.015, null], ["预备费率", 0.05, null], ["备注", "本表为合成样本", null]] },
6
+ { "op": "write", "sheet": "计算", "range": "A1", "values": [["项目", "金额"], ["建安费", { "formula": "=假设!B2*假设!B3" }], ["设计费", { "formula": "=B2*假设!B4" }], ["监理费", { "formula": "=B2*假设!B5" }], ["小计", { "formula": "=SUM(B2:B4)" }], ["预备费", { "formula": "=B5*假设!B6" }]] },
7
+ { "op": "write", "sheet": "汇总", "range": "A1", "values": [["指标", "数值"], ["总投资", { "formula": "=计算!B5+计算!B6" }], ["单方指标", { "formula": "=B2/假设!B2" }], ["生成日期", { "formula": "=TODAY()" }]] },
8
+ { "op": "name.set", "name": "总投资", "reference": "汇总!$B$2" },
9
+ { "op": "format", "sheet": "计算", "range": "B2:B6", "style": { "numberFormat": "#,##0.00" } },
10
+ { "op": "format", "sheet": "汇总", "range": "B2:B3", "style": { "numberFormat": "#,##0.00" } }
11
+ ]
12
+ }
@@ -0,0 +1,35 @@
1
+ # 按条件批量修改记录并读回结果
2
+
3
+ 按列条件数出匹配的记录,只对这一批记录做修改,只重算关心的结果并读回。
4
+
5
+ ## 运行
6
+
7
+ 在本目录下依次执行:
8
+
9
+ 1. `excel-kit script request.json`:生成 `trading-table-updated.xlsx`。
10
+
11
+ `request.json` 里的路径相对本目录。脚本本体是 `recipe.js`,开头的注释列出了全部参数。
12
+
13
+ ## 参数
14
+
15
+ `target` 与 `where` 是选择条件;`set` 是要写入的列值;`read` 是要重算并返回的范围;`expectMatches` 可选,用来防止条件写错。
16
+
17
+ ## 样本与许可
18
+
19
+ `sample/trading-table.xlsx` 是本仓库第三阶段用 XlsxWriter 合成的 Table 样本,可再分发。
20
+
21
+ ## 样本上的结果
22
+
23
+ 数量不小于 2 的两条记录单价改为 9.9:1 月汇总 49.5,2 月汇总 20。
24
+
25
+ ## 要点
26
+
27
+ - 编辑步骤带 `expectedMatches`,匹配数量与刚才数到的不一致就拒绝执行(`SELECTION_COUNT_MISMATCH`)。它只核对数量,不核对是哪几条;先数和修改在同一个脚本事务里,中间不会有别的写入。
28
+ - 修改、只算 `read` 列出的结果、读取在同一步。交付件里只保证这些结果是当前值;其余受这次修改影响的公式没有值,保存时有 `FORMULAS_WITHOUT_VALUES` 警告。
29
+ - 没有匹配是正常结果:不写文件,`output.saved:false`。
30
+
31
+ ## 结果算不完整时
32
+
33
+ 依次运行 `excel-kit run prepare-incomplete.json`、`excel-kit script incomplete.json`:前者在样本的月汇总 D2 写入未知函数,后者仍修改两条记录并发布 `incomplete-updated.xlsx`。D2 不写占位错误值,返回结果为 null;这表示不可得,不能当成计算出的空值。`script.result.unavailable` 给出计数、示例、stepId,完整清单由顶层 `calculationReport.path` 指向。按行读取 JSONL:第一行是步骤版本、计算条件、数量和摘要,后续是逐格压缩记录;核对记录数、展开格数及摘要。
34
+
35
+ 需要旧行为时运行 `excel-kit script incomplete-strict.json`,它设置 `requireCompleteCalculation:true`,被分组 wb.run 继承;本例会回滚且不写文件。`strict:true` 只让失败调用抛错,不会把默认成功的 incomplete 改成失败。正常配方也可按需在请求顶层加此发布选项。
@@ -0,0 +1,33 @@
1
+ {
2
+ "input": "incomplete-input.xlsx",
3
+ "output": "incomplete-strict.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "target": {
8
+ "kind": "rows",
9
+ "table": "交易明细"
10
+ },
11
+ "where": {
12
+ "column": "数量",
13
+ "operator": "gte",
14
+ "value": 2
15
+ },
16
+ "set": [
17
+ {
18
+ "column": "单价",
19
+ "value": 9.9
20
+ }
21
+ ],
22
+ "read": [
23
+ {
24
+ "sheet": "月汇总",
25
+ "range": "D2"
26
+ }
27
+ ]
28
+ },
29
+ "calculation": {
30
+ "mode": "none"
31
+ },
32
+ "requireCompleteCalculation": true
33
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "input": "incomplete-input.xlsx",
3
+ "output": "incomplete-updated.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "target": {
8
+ "kind": "rows",
9
+ "table": "交易明细"
10
+ },
11
+ "where": {
12
+ "column": "数量",
13
+ "operator": "gte",
14
+ "value": 2
15
+ },
16
+ "set": [
17
+ {
18
+ "column": "单价",
19
+ "value": 9.9
20
+ }
21
+ ],
22
+ "read": [
23
+ {
24
+ "sheet": "月汇总",
25
+ "range": "D2"
26
+ }
27
+ ]
28
+ },
29
+ "calculation": {
30
+ "mode": "none"
31
+ }
32
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "input": "sample/trading-table.xlsx",
3
+ "output": "incomplete-input.xlsx",
4
+ "calculation": {
5
+ "mode": "none"
6
+ },
7
+ "operations": [
8
+ {
9
+ "op": "write",
10
+ "sheet": "月汇总",
11
+ "range": "D2",
12
+ "values": [
13
+ [
14
+ {
15
+ "formula": "=UNKNOWN_FUNCTION(1)"
16
+ }
17
+ ]
18
+ ]
19
+ }
20
+ ]
21
+ }
@@ -0,0 +1,35 @@
1
+ // Find the records that match a column condition, change them in one step,
2
+ // recalculate only the results you care about and read them back.
3
+ //
4
+ // args: { target, where, set, read, expectMatches? }
5
+ // target selection target, e.g. { kind: 'rows', table: '交易明细' }
6
+ // where selection condition, e.g. { column: '数量', operator: 'gte', value: 2 }
7
+ // set [{ column, value }] applied to every matching row
8
+ // read [{ sheet, range }] results to recalculate and return
9
+ const must = (response, what) => {
10
+ if (!response.ok) {
11
+ const first = response.calculation?.diagnostics?.[0];
12
+ throw new Error(response.error ? `${what}: ${response.error.code} ${response.error.message}` : `${what}: CALCULATION_INCOMPLETE calculation ${response.calculation?.status}${first ? ` (${first.code} at ${first.sheet}!${first.cell}: ${first.message})` : ''}`);
13
+ }
14
+ return response;
15
+ };
16
+ const select = { target: args.target, where: args.where };
17
+ const found = must(await wb.query({ select: [{ ...select, limit: 1 }] }), 'Select').select[0];
18
+ if (args.expectMatches !== undefined && found.total !== args.expectMatches) throw new Error(`Expected ${args.expectMatches} matching records, found ${found.total}.`);
19
+ if (found.total === 0) return { matched: 0, changed: false, results: [] };
20
+
21
+ // expectedMatches makes the edit refuse to run if the number of matches differs from the one just counted.
22
+ // Edit, calculate just the requested results and read them in the same step.
23
+ const edit = await wb.run({
24
+ operations: [{ op: 'selection.edit', selection: select, action: { kind: 'set', values: args.set }, expectedMatches: found.total }],
25
+ calculation: { mode: 'targets', targets: args.read }, read: args.read,
26
+ }).catch(error => error.response);
27
+ if (!edit.ok) {
28
+ const first = edit.error?.details?.diagnostics?.[0];
29
+ throw new Error(`Edit failed: ${edit.error.code} ${edit.error.message}${first ? ` (${first.code} at ${first.sheet}!${first.cell})` : ''}`);
30
+ }
31
+ return {
32
+ matched: found.total, changed: true,
33
+ ...(edit.result.calculation.status === 'incomplete' ? { unavailable: edit.result.calculation.unavailable } : {}),
34
+ results: edit.result.ranges.map(range => ({ sheet: range.sheet, range: range.range, values: range.cells.map(row => row.map(cell => cell.result?.value ?? null)) })),
35
+ };
@@ -0,0 +1,29 @@
1
+ {
2
+ "input": "sample/trading-table.xlsx",
3
+ "output": "trading-table-updated.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "target": {
8
+ "kind": "rows",
9
+ "table": "交易明细"
10
+ },
11
+ "where": {
12
+ "column": "数量",
13
+ "operator": "gte",
14
+ "value": 2
15
+ },
16
+ "set": [
17
+ {
18
+ "column": "单价",
19
+ "value": 9.9
20
+ }
21
+ ],
22
+ "read": [
23
+ {
24
+ "sheet": "月汇总",
25
+ "range": "A2:B3"
26
+ }
27
+ ]
28
+ }
29
+ }
@@ -0,0 +1,59 @@
1
+ # 会话协议
2
+
3
+ 给自己实现 `excel-kit session` 客户端的人;只用命令行不需要读这一篇。字段查 `excel-kit help`;调用方式的契约在 `SKILL.md`,会话怎样用见 [sessions.md](sessions.md)。
4
+
5
+ ## 1. 会话协议
6
+
7
+ `excel-kit session` 在标准输入输出上说换行分隔的 JSON-RPC 2.0:每行一个 JSON 对象,不支持批量数组,标准输出只有协议消息。请求按到达顺序逐个执行,一个进程里的多个会话也是串行的。
8
+
9
+ ```json rpc
10
+ {"jsonrpc":"2.0","id":1,"method":"session.open","params":{"sessionId":"s","input":"input.xlsx","output":"output.xlsx"}}
11
+ {"jsonrpc":"2.0","id":2,"method":"session.run","params":{"sessionId":"s","op":"write","sheet":"Sheet1","range":"B2","values":[[1200]]}}
12
+ {"jsonrpc":"2.0","id":3,"method":"session.save","params":{"sessionId":"s"}}
13
+ ```
14
+
15
+ 应答有三种样子,按 `id` 对应请求:
16
+
17
+ ```json response
18
+ {"jsonrpc":"2.0","id":2,"result":{"session":{"id":"s","version":"<SHA-256>"},"elapsedMs":41.2,"queuedMs":0.3,"response":{"ok":true,"status":"succeeded","inputVersion":"<SHA-256>","outputVersion":"<SHA-256>","result":{}}}}
19
+ ```
20
+
21
+ ```json response
22
+ {"jsonrpc":"2.0","id":2,"result":{"session":{"id":"s","version":"<SHA-256>"},"elapsedMs":12.5,"queuedMs":0.3,"response":{"ok":false,"status":"failed","inputVersion":"<SHA-256>","error":{"code":"SHEET_NOT_FOUND","message":"Worksheet does not exist.","details":{}}}}}
23
+ ```
24
+
25
+ ```json response
26
+ {"jsonrpc":"2.0","id":4,"error":{"code":-32601,"message":"Unknown method."}}
27
+ ```
28
+
29
+ - `result.response` 是该方法的业务响应,业务失败也在这里;顶层的 `error` 只报协议错误,这一行没有被当作请求执行。
30
+ - `result.session.version` 是当前内存字节的 SHA-256,与读取、查询响应里的 `workbookVersion` 是同一个值。`elapsedMs` 是执行时长,排队时长在 `queuedMs`。
31
+ - 应答不保证与请求同序:一行的格式、`id`、方法名、`params` 不对时立即应答,可能排在更早请求的应答之前。
32
+
33
+ | 协议错误 | 含义 |
34
+ |---|---|
35
+ | `-32700` | 该行不是合法 JSON;应答的 `id` 是 `null` |
36
+ | `-32600` | 不是合法请求:不是对象、缺 `jsonrpc` 或 `method`、缺 `id`,或 `id` 属于一个还没结束的请求 |
37
+ | `-32601` | 未知方法 |
38
+ | `-32602` | `params` 不是对象;`sessionId` 缺失或不是字符串(`session.open` 自选的要 1–128 个字符) |
39
+ | `-32001` | 未知会话:没有打开过,或已经关闭。轮到这条请求执行时才判,所以打开与后续调用可以一起管入 |
40
+
41
+ `id` 只接受字符串或数字,`1` 与 `"1"` 是不同的 id。像 JSON-RPC,不像的地方是除 `$/cancel` 外每条消息都必须带 `id`:缺 `id` 的消息得到 `-32600`,不会被静默执行。
42
+
43
+ 取消用通知 `{"jsonrpc":"2.0","method":"$/cancel","params":{"id":<请求 id>}}`:排队中的请求立即以 `CANCELLED` 应答,运行中的步骤以 `CANCELLED` 失败且不改状态,运行中的脚本整体回滚;未知或已结束的 id 被忽略。
44
+
45
+ 结束:
46
+
47
+ - 标准输入关闭后,已收到的请求全部执行并应答,然后丢弃未保存的状态,退出码 0。
48
+ - SIGINT、SIGTERM:停止读入,取消运行中的调用,排队中的请求逐条以 `CANCELLED` 应答,退出码 130。Windows 上没有 SIGTERM,用 `$/cancel` 取消、用关闭标准输入结束。
49
+ - 标准输出管道断开:中止运行中的调用,退出码 1。
50
+
51
+ 一个进程可以打开多个会话,每个持有一份工作簿字节,不设数量上限;要并行就启动多个进程。两个会话指向同一个目标文件时,保存时的版本核对保证后保存的一方不会悄悄覆盖先保存的。会话不是守护进程:没有端口、鉴权和后台常驻,生命周期就是这个子进程。
52
+
53
+ ## 2. 退出码
54
+
55
+ 响应 `ok:false` 是 1,其中 `error.code` 为 `CANCELLED` 是 130,其余是 0。所以 0 不等于做成了:一次性脚本有失败步骤、甚至一步都没成功时是 0;会话在输入结束后退出也是 0,不论其中有多少业务失败。
56
+
57
+ ## 3. Node.js 与其他客户端
58
+
59
+ 本发行包提供独立命令行程序,不导出内核库。使用子进程调用 CLI,或通过标准输入输出连接上述会话协议。Node.js 可用 `child_process.spawn`;参数用数组传入,不需要 shell。
@@ -0,0 +1,50 @@
1
+ # 找出算不出来的公式与影响范围
2
+
3
+ 整本计算不完整时,怎样列出问题、追到源头、查清一处改动影响到哪里。不支持的原因见 [unsupported.md](unsupported.md),字段查 `help query.findings`、`help query.dependencies`。
4
+
5
+ ## 问题清单:`findings`
6
+
7
+ - `query` 加 `"calculation":{"mode":"all"}` 和 `findings`,就是 `audit` 的默认行为。计算不完整时查询仍是 `ok:true`,要自己看 `calculation.status`。
8
+ - `findings.items` 不全是算不出来的格:`kind` 为 `diagnostic` 的是诊断(`code` 是原因,如 `UNSUPPORTED_FUNCTION`),`cache_difference` 是本次结果与文件里存值不同的格。按 `kind` 与 `classification` 筛。
9
+ - 默认每页 100 条,`limit` 让一页多取;`findings.nextOffset` 不为 `null` 还有下一页。`assessment` 是汇总:已确认的错误、不可得、存值差异各多少。
10
+
11
+ ## 引用关系:`dependencies`
12
+
13
+ - 查一个格的上游(`"direction":"precedents"`)或下游(`"dependents"`),加 `"transitive":true` 一直追到头。名称会展开,比自己解析公式可靠。
14
+ - 结果与请求一一对应。条目用 `sheet` 加 `range` 定位,`range` 可能是一块区域;`nextOffset` 不为 `null` 还有下一页。
15
+ - 它只给**静态**引用,也就是公式里写明的。`INDIRECT`、`OFFSET` 这类运行时才定的区域不在其中:结果的 `limitations.count` 大于 0,`items` 里标出是哪些格(如 `RUNTIME_REFERENCES_PENDING`)。这时即使翻完所有页,也不是完整的影响范围;用它组计算目标或说明影响之前先看 `limitations`。
16
+ - 要判断一个上游格是输入还是公式,读回它看 `kind`,紧凑形式看有没有 `f`。
17
+
18
+ ## 整本算不完整时
19
+
20
+ 默认 all 计算不完整仍保存可靠结果,先读 calculation.unavailable.report 指向的 JSONL 清单。显式 requireCompleteCalculation:true 的 all 被拒绝、没有写文件时:
21
+
22
+ 1. 读错误 `details` 里的诊断,按格找出不可得的源头:不支持的函数、外部引用、循环、模拟运算表、打开时刷新的透视。要列全就用上面的 `findings`。
23
+ 2. 用 `dependents` 加 `transitive` 查这些源头影响到的格,先看 `limitations`。
24
+ 3. 任务要的结果里,不受影响的那些作为 `targets` 计算。这是按交付要求缩小范围,不是绕过失败:受影响的结果仍然没有。
25
+ 4. 报告里写清哪些是本次结果,哪些没有值或没有更新,各自是什么原因;不要笼统地说"源文件有错"。
26
+
27
+ 修复时,互相牵连的问题(多个循环、未知函数)要在同一步里改,否则中间状态仍算不出来;改完再审计一次。包里的配方 `recipes/audit-and-repair` 是完整的做法。
28
+
29
+ ## 例
30
+
31
+ 一份查询同时要问题清单和两处引用关系:
32
+
33
+ ```sh
34
+ cat > audit.json <<'EOF'
35
+ {"input":"input.xlsx","calculation":{"mode":"all"},
36
+ "findings":{"limit":1000},
37
+ "dependencies":[{"sheet":"Sheet1","cell":"B10","direction":"precedents","transitive":true},
38
+ {"sheet":"Data","cell":"C2","direction":"dependents","transitive":true}]}
39
+ EOF
40
+ ./excel-kit query audit.json > audit.out.json || true
41
+ python3 - <<'EOF'
42
+ import json
43
+ d = json.load(open('audit.out.json'))
44
+ if not d['ok']:
45
+ raise SystemExit(f"failed: {json.dumps(d['error'])}")
46
+ print(d['calculation']['status'], d['assessment'], len(d['findings']['items']), d['findings']['nextOffset'])
47
+ for dep in d['dependencies']:
48
+ print(dep['limitations']['count'], dep['nextOffset'], [(i['sheet'], i['range']) for i in dep['items']][:3])
49
+ EOF
50
+ ```