@dztabel/excel-kit 0.0.0-stage → 0.10.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 (97) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/DISTRIBUTION.md +13 -0
  3. package/LICENSE +45 -0
  4. package/README.md +74 -2
  5. package/SKILL.md +52 -0
  6. package/THIRD-PARTY-NOTICES.txt +3050 -0
  7. package/VALIDATION.md +46 -0
  8. package/bin/excel-kit.cjs +50 -0
  9. package/package.json +19 -4
  10. package/recipes/README.md +31 -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/repair-and-test-model/README.md +13 -0
  55. package/recipes/repair-and-test-model/workflow.py +108 -0
  56. package/recipes/roll-forward-period/README.md +30 -0
  57. package/recipes/roll-forward-period/prepare.json +10 -0
  58. package/recipes/roll-forward-period/recipe.js +49 -0
  59. package/recipes/roll-forward-period/request.json +13 -0
  60. package/recipes/roll-forward-period/sample/budget-template.xlsx +0 -0
  61. package/recipes/style-matching-sheets/README.md +28 -0
  62. package/recipes/style-matching-sheets/recipe.js +38 -0
  63. package/recipes/style-matching-sheets/request.json +17 -0
  64. package/recipes/style-matching-sheets/sample/build-workbook.request.json +13 -0
  65. package/recipes/style-matching-sheets/sample/report-tables.xlsx +0 -0
  66. package/recipes/update-assumptions/README.md +29 -0
  67. package/recipes/update-assumptions/recipe.js +66 -0
  68. package/recipes/update-assumptions/request.json +10 -0
  69. package/recipes/update-assumptions/sample/build-model.request.json +12 -0
  70. package/recipes/update-assumptions/sample/cost-model.xlsx +0 -0
  71. package/recipes/update-matching-records/README.md +35 -0
  72. package/recipes/update-matching-records/incomplete-strict.json +33 -0
  73. package/recipes/update-matching-records/incomplete.json +32 -0
  74. package/recipes/update-matching-records/prepare-incomplete.json +21 -0
  75. package/recipes/update-matching-records/recipe.js +35 -0
  76. package/recipes/update-matching-records/request.json +29 -0
  77. package/recipes/update-matching-records/sample/trading-table.xlsx +0 -0
  78. package/reference/api.md +59 -0
  79. package/reference/audit.md +50 -0
  80. package/reference/calculation.md +82 -0
  81. package/reference/cost.md +61 -0
  82. package/reference/deliverable.md +66 -0
  83. package/reference/editing-and-saving.md +69 -0
  84. package/reference/errors.md +65 -0
  85. package/reference/external-links.md +39 -0
  86. package/reference/function-limits.md +30 -0
  87. package/reference/paging.md +63 -0
  88. package/reference/pivots.md +46 -0
  89. package/reference/presentation.md +11 -0
  90. package/reference/protection.md +63 -0
  91. package/reference/reading.md +70 -0
  92. package/reference/scripts.md +74 -0
  93. package/reference/selection.md +43 -0
  94. package/reference/session-loop.md +62 -0
  95. package/reference/sessions.md +54 -0
  96. package/reference/unsupported.md +31 -0
  97. package/release.json +41 -0
package/VALIDATION.md ADDED
@@ -0,0 +1,46 @@
1
+ # 0.10.0 验证范围
2
+
3
+ Windows 11 上的 Microsoft Excel 16.0 build 20326 已对新增的图表系列、原生统计图、透视分组与过滤以及展示规则进行编辑并保存复核。组合示例中,迁移后的公式和图表随数量调整从 36 变为 42;条件透视总计从 0.27 变为 0.5。合并标题在 15 磅行高下截断,在 70 磅下完整显示。文字截断查询使用布局估计。固定版 SDK 对部分 Excel 接受的统计图分箱标记仍报告差异。
4
+
5
+ 本版沿用开发时的源码回归和定向复核,共 3,099 个有效用例有通过记录,5 项既有跳过。随包说明按专题核对,组合示例实际交付可编辑文件。发行安装核对另见 DISTRIBUTION.md。
6
+
7
+ ## 0.9.0 历史验证范围
8
+
9
+
10
+ 本版降低大工作簿的计算与保存内存占用,修正查找空值、原生透视结果读取及 EXP 舍入问题。这里区分实际通过、有效历史证据复用和仍保留的例外;不把程序成功保存等同于整本公式都与 Excel 一致。
11
+
12
+ ## 已有验证
13
+
14
+ | 项目 | 结果 |
15
+ |---|---|
16
+ | 142 份既有工作簿 | 138 次查询、142 次整本另存的首次操作均低于 8 GiB,最高约 7.30 GiB;保存核验通过。H2A 一页首次超时,原样有限补证成功,首次失败仍保留 |
17
+ | c016 财务模型 | 整本另存约 5.01 GiB,保存的 356,434 个可比格全部与 Excel 相同 |
18
+ | 78 行固定资源矩阵 | 全部低于 240 秒/8 GiB;CA32 读回约 955 MiB、NREL 追溯约 1,077 MiB,达到 1,088 MiB 预算。CA32 两条写入约 2,684/2,682 MiB,未达到各自 2,112 MiB 的历史预算;旧版也存在,保留为明确接受的发行例外 |
19
+ | 12 份额外工作簿 | 迁移与保存核验全部通过;11/12 整本可比值全对,C074 的既有差异未扩大。首次 C067 有 14 格超容差,通用 EXP 修正后其保存件 1,127,160 个可比格全部正确;这是修正后回归,不是首次全部通过 |
20
+ | Excel 重开 | 先前有效记录按文件身份复用;最终增量的 5 份文件、632,586 个可比格全部相同。EXP 修正后 4 份变化保存件再次重开,207,157 个可比格全部相同,无修复提示或结构损失 |
21
+ | 三平台 | macOS ARM64 原生、macOS x64 经 Rosetta、Windows x64 在 Windows ARM64 来宾中仿真。每平台的 26 项接口、48 项语义、20 次强杀与后续写入恢复通过;最终 EXP 增量每平台 26 项通过 |
22
+ | 构建与源码检查 | 两次干净构建的三平台程序逐字节相同,并与最终验收程序一致。既有全量检查与帮助断言修正后的定向检查合并覆盖 3,084 项有效测试,5 项跳过,0 项未解决失败;未因本次发行重复整套实验 |
23
+
24
+ 最终 EXP 修正只对受影响工作簿做增量回归,其余有效证据保留原程序身份。单元格值按各自既定比较口径判断,不能由这些计数推断任意公式都能与 Excel 按位一致。
25
+
26
+ ## 已知边界
27
+
28
+ - 资源数字来自 macOS ARM64、32 GiB 主机,不能外推为 16 GiB 设备或其他平台的保证。额外语料 C046、C067 分别约 9.74/8.90 GiB,超过 8 GiB;8 GiB 不是产品的通用上限。
29
+ - H2A 首次真实超时的根因未确定,有限补证成功不抹去首次失败。
30
+ - 未标记 `refreshOnLoad="1"` 的透视输出可用其当前保存值作公式输入;这不代表本次刷新了透视。兼容证据限 Excel 重算且不刷新透视的行为。
31
+ - EXP 的 24 个输入与两个抵消结果与 Excel 逐位相同,不代表覆盖全部浮点输入。
32
+ - 查找空值再经 `ISBLANK`、`ISNUMBER`、连接、`LEN` 的组合,以及原件已标记 `invalid="1"` 的透视,仍缺专门 Excel 实测。
33
+ - 既有函数差异、循环引用、外部材料缺失等可能使计算不完整。`ok:true` 不等于整本算完;查看计算状态、不可得清单及结果来源。
34
+ - 本版没有重做历史 agent 任务、WPS 编辑往返,也没有完成 Desktop 接入。VBA、加密文件及其他边界见 [unsupported.md](reference/unsupported.md)。
35
+
36
+ ## 公开发行身份
37
+
38
+ CLI `0.9.0`,协议 `1`,内嵌运行时 Bun `1.4.2`。本次 npm/公开 Release 直接复用已验收的三个程序,不重新编译。安装入口、许可和用户文档单独整理,因此公开 ZIP 摘要与先前发行包不同,二进制摘要保持不变。
39
+
40
+ | 平台 | 程序 SHA-256 |
41
+ |---|---|
42
+ | macOS ARM64 | `6ee295691e30c622ad1e37aebb930b72b3085df2eb32c972bb3db67d89df31e0` |
43
+ | macOS x64 | `452e94386788d83f0f75cf0028074a5a0698184a972ce5f8e75b727f82b61773` |
44
+ | Windows x64 | `25a12c8356fbb7a30a0bc58ef9b16c994d37a7c680364267cc8c603ab113533f` |
45
+
46
+ [release.json](release.json) 给出完整构建身份;发行页的 `SHA256SUMS` 校验 ZIP。npm 安装入口的检查单独记录在 [DISTRIBUTION.md](DISTRIBUTION.md),不把打包检查计作新的工作簿验收。
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { spawn } = require('node:child_process');
5
+ const { join, dirname } = require('node:path');
6
+ const { constants } = require('node:os');
7
+ const { version } = require('../package.json');
8
+
9
+ function platformPackage(platform, arch) {
10
+ // The Windows x64 binary also runs under Windows ARM64 emulation.
11
+ if (platform === 'win32' && (arch === 'x64' || arch === 'arm64')) return '@dztabel/excel-kit-win32-x64';
12
+ if (platform === 'darwin' && (arch === 'arm64' || arch === 'x64')) return `@dztabel/excel-kit-darwin-${arch}`;
13
+ throw new Error(`Unsupported platform ${platform}/${arch}. This release supports macOS arm64/x64 and Windows x64 (including Windows ARM64 emulation).`);
14
+ }
15
+
16
+ function main() {
17
+ let executable;
18
+ try {
19
+ const name = platformPackage(process.platform, process.arch);
20
+ let manifestPath;
21
+ try { manifestPath = require.resolve(`${name}/package.json`); }
22
+ catch { throw new Error(`Missing ${name}@${version}. Reinstall with npm install --include=optional @dztabel/excel-kit@${version} (add -g for a global installation).`); }
23
+ const installed = require(manifestPath);
24
+ if (installed.version !== version) throw new Error(`Expected ${name}@${version}, found ${installed.version}. Reinstall @dztabel/excel-kit@${version}.`);
25
+ executable = join(dirname(manifestPath), 'bin', process.platform === 'win32' ? 'excel-kit.exe' : 'excel-kit');
26
+ } catch (error) {
27
+ process.stderr.write(`excel-kit: ${error.message}\n`);
28
+ process.exitCode = 1;
29
+ return;
30
+ }
31
+
32
+ const child = spawn(executable, process.argv.slice(2), { stdio: 'inherit', windowsHide: true });
33
+ const signals = ['SIGINT', 'SIGTERM'];
34
+ const handlers = new Map(signals.map(signal => [signal, () => { if (child.exitCode === null) child.kill(signal); }]));
35
+ for (const [signal, handler] of handlers) process.on(signal, handler);
36
+ function unhook() { for (const [signal, handler] of handlers) process.removeListener(signal, handler); }
37
+ child.once('error', error => {
38
+ unhook();
39
+ process.stderr.write(`excel-kit: Cannot start the installed program: ${error.message}\n`);
40
+ process.exitCode = 1;
41
+ });
42
+ child.once('exit', (code, signal) => {
43
+ unhook();
44
+ if (signal && process.platform !== 'win32') process.kill(process.pid, signal);
45
+ else process.exitCode = code ?? (128 + (constants.signals[signal] || 1));
46
+ });
47
+ }
48
+
49
+ if (require.main === module) main();
50
+ module.exports = { platformPackage };
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@dztabel/excel-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.10.0",
4
+ "description": "Read, edit, calculate and save Excel workbooks from your agent or terminal.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "repository": { "type": "git", "url": "git+https://github.com/dztabel-happy/excel-kit.git" },
7
+ "homepage": "https://github.com/dztabel-happy/excel-kit#readme",
8
+ "bugs": { "url": "https://github.com/dztabel-happy/excel-kit/issues" },
9
+ "keywords": ["excel", "xlsx", "xlsm", "cli", "agent", "spreadsheet"],
10
+ "bin": { "excel-kit": "bin/excel-kit.cjs" },
11
+ "engines": { "node": ">=20" },
12
+ "os": ["darwin", "win32"],
13
+ "cpu": ["arm64", "x64"],
14
+ "files": ["bin/", "SKILL.md", "reference/", "recipes/", "VALIDATION.md", "CHANGELOG.md", "DISTRIBUTION.md", "THIRD-PARTY-NOTICES.txt", "release.json"],
15
+ "optionalDependencies": {
16
+ "@dztabel/excel-kit-darwin-arm64": "0.10.0",
17
+ "@dztabel/excel-kit-darwin-x64": "0.10.0",
18
+ "@dztabel/excel-kit-win32-x64": "0.10.0"
19
+ },
20
+ "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" }
21
+ }
@@ -0,0 +1,31 @@
1
+ # 配方
2
+
3
+ 每个配方是一段在工作簿事务内运行的脚本(见 `excel-kit help script`),只用公开的命令与操作,附可再分发的样本和说明。
4
+
5
+ 进入配方目录,按该目录 README 的步骤执行;需要预置内容的先执行 `excel-kit run prepare.json`。输出写在配方目录里;同名输出已存在时拒绝覆盖,再试一次就换一个输出名。用于自己的文件时,改 `request.json` 的 `input`、`output` 和 `arguments`,保留 `scriptPath`。脚本什么时候发布见 `SKILL.md` 第 2 条:正常返回后发布成功的步骤,抛错则什么都不写。
6
+
7
+ | 编号 | 目录 | 做什么 | 组合一次性命令 |
8
+ |---|---|---|---|
9
+ | R1 | [roll-forward-period](roll-forward-period/README.md) | 滚动到下一期间 | 否 |
10
+ | R2 | [update-matching-records](update-matching-records/README.md) | 按条件批量修改记录并读回结果 | 否 |
11
+ | R3 | [import-clean-append](import-clean-append/README.md) | 导入 CSV、清洗、去重并追加到 Table | 否 |
12
+ | R4 | [fill-template](fill-template/README.md) | 填写模板、校验、加打印设置与保护 | 否 |
13
+ | R5 | [audit-and-repair](audit-and-repair/README.md) | 巡检公式问题并应用选定的修正 | 否 |
14
+ | R6 | [update-assumptions](update-assumptions/README.md) | 只改指定假设并返回结果的静态上游 | 否 |
15
+ | R7 | [style-matching-sheets](style-matching-sheets/README.md) | 对名称匹配的工作表批量设置格式、打印与视图 | 否 |
16
+ | R8 | [normalize-codes](normalize-codes/README.md) | 用正则在整本工作簿里规范化编号 | 否 |
17
+ | R9 | [pivot-by-slicer](pivot-by-slicer/README.md) | 追加明细、刷新透视,按切片器逐项读取下游公式 | 否 |
18
+ | R10 | [inventory-media](inventory-media/README.md) | 清点图片与附件并提取核对 | `image-extract`、`attachment-extract` |
19
+ | R11 | [edit-protected-workbook](edit-protected-workbook/README.md) | 保存无口令保护权限、编辑并恢复核对;带口令时拒绝 | 先 `run prepare.json` 准备示例 |
20
+
21
+ [修复模型并试算两个情景](repair-and-test-model/README.md)使用同一份工作簿组合版本比较、局部迁移、试算、精细重读、条件透视与布局检查。
22
+
23
+ ## 写自己的脚本时
24
+
25
+ - **能事先写全就不用脚本。** 一份 `run` 把改动、计算、读取写在一起;脚本只用在下一步取决于上一步结果的时候。
26
+ - **请求写 `strict:true`。** 配方的请求都带它:任何一次 `wb.*` 失败直接抛出,脚本整体回滚,原错误在 `error.details.cause`。要自己处理某一次失败,只捕获那一次并拿回原响应:`.catch(error => error.response)`(`fill-template`、`update-matching-records` 各有一处)。不带 `strict` 时失败的调用返回 `ok:false`,每次取值前都得自己判;配方的脚本两样都做了,所以换一份不带 `strict` 的请求调用也报原错误。
27
+ - **先数再改,改完看改了谁。** 用查询数出匹配数量,编辑时带 `expectedMatches`,数量不符就拒绝。它只核对个数;条件用到公式的值要写 `source:"calculation"`。
28
+ - **让步骤失败,而不是自己判断。** 要校验就用步骤的 `validate`,要整本算完才接受步骤,就明确写 `requireCompleteCalculation:true`;默认计算不完整也可接受步骤并发布可得值,须检查计算状态和不可得清单。失败的步骤不留下任何修改。
29
+ - **该放一步的放一步。** 互相依赖的修改(修循环引用、追加后重新应用筛选、改透视来源后刷新透视)必须在同一步;要读这一步算出的值,把 `read` 也写进这一步。
30
+ - **发布前自证。** 用同一个搜索证明零残留,用独立求和核对小计,用第二次审计证明干净;不满足就 `throw`,脚本整体回滚。
31
+ - **`wb` 没有通用文件接口。** CSV 用 `data` 操作导入暂存表再读回;图片与附件的提取交给一次性命令。脚本不是安全沙箱,宿主的文件与网络访问不受工作簿事务回滚保护。
@@ -0,0 +1,30 @@
1
+ # 巡检公式问题并应用选定的修正
2
+
3
+ 对整本工作簿做计算审计,找出失效引用、未知函数、循环引用和公式错误,区分问题的源头和只是受累的单元格;给出修正后,只有第二次审计干净且声明的业务规则全部成立才发布。
4
+
5
+ ## 运行
6
+
7
+ 在本目录下依次执行:
8
+
9
+ 1. `excel-kit script inspect.json`:只巡检,返回候选清单,不写文件。
10
+ 2. `excel-kit script request.json`:应用 `fixes`,生成 `model-repaired.xlsx`。
11
+
12
+ `request.json` 里的路径相对本目录。脚本本体是 `recipe.js`,开头的注释列出了全部参数。
13
+
14
+ ## 参数
15
+
16
+ `fixes` 是选定的修正(`sheet`、`cell`、`formula`);针对审计没有标记的单元格的修正要标 `businessRule:true`;`assertions` 是修复后必须成立的业务断言。
17
+
18
+ ## 样本与许可
19
+
20
+ `sample/model-to-check.xlsx` 与 `sample/clean-control.xlsx` 来自本仓库第二阶段模型检查证据的归档 `docs/goals/phase-03-workbook-maintenance/evidence/model-audit/raw.tar.gz`(成员 `model-audit/old-task-02/待检查 模型.xlsx` 与 `正常 对照.xlsx`),由 `scripts/validation/audit.py` 的独立写入器合成,属仓库自生成,可再分发。SHA-256 分别为 `31d49d5a…eda2d` 与 `5b56b3a6…aa4f`。`sample/expected.json` 是从该脚本的常量手工抄出的注入清单与修正值。
21
+
22
+ ## 样本上的结果
23
+
24
+ 巡检指出 5 个源头(B3 失效引用、B4 与 B5 循环、B6 未知函数、B10 除零)和 5 个受累单元格;修复后审计为零,三条业务断言通过,公式与正常对照逐格相同。
25
+
26
+ ## 要点
27
+
28
+ - 全部修正放在同一步:循环或未知函数还在时整本无法完成计算,逐个修会每一步都失败。
29
+ - B1、B2 两处业务错误能正常计算,任何审计都看不出来,只能靠声明的业务规则发现。
30
+ - 少修一处循环,配方拒绝发布。
@@ -0,0 +1,7 @@
1
+ {
2
+ "input": "sample/model-to-check.xlsx",
3
+ "output": "unused.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {}
7
+ }
@@ -0,0 +1,48 @@
1
+ // Audit a whole workbook for formulas that cannot be trusted (broken
2
+ // references, unknown functions, cycles, errors), report where each problem
3
+ // originates, and apply the corrections that were chosen for them. Without
4
+ // args.fixes it only inspects. With fixes it publishes only if the second
5
+ // audit is clean and every stated business rule holds.
6
+ //
7
+ // args: { fixes?, assertions? }
8
+ // fixes [{ sheet, cell, formula }] corrections chosen after reading the candidates
9
+ // assertions query assertions ({ id, basis, kind, ... }) that must pass after the repair
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 audit = async () => must(await wb.query({ calculation: { mode: 'all' }, findings: { limit: 1000 }, ...(args.assertions ? { assertions: args.assertions } : {}) }), 'Audit');
18
+ const key = item => `${item.sheet}!${item.cell}`;
19
+
20
+ const before = await audit();
21
+ const diagnostics = before.findings.items.filter(item => item.kind === 'diagnostic');
22
+ const byCell = new Map();
23
+ for (const item of diagnostics) { const entry = byCell.get(key(item)) ?? { sheet: item.sheet, cell: item.cell, codes: [], messages: [] }; entry.codes.push(item.code); entry.messages.push(item.message); byCell.set(key(item), entry); }
24
+
25
+ // A problem cell is an origin when none of the cells it reads is itself a problem; otherwise it only inherits one.
26
+ const cells = [...byCell.values()];
27
+ const precedents = cells.length ? must(await wb.query({ dependencies: cells.map(entry => ({ sheet: entry.sheet, cell: entry.cell, direction: 'precedents' })) }), 'Read precedents').dependencies : [];
28
+ const inCycle = entry => entry.codes.includes('CIRCULAR_REFERENCE');
29
+ const candidates = cells.map((entry, index) => {
30
+ const reads = precedents[index].items.map(item => `${item.sheet}!${item.range}`);
31
+ const inherited = reads.filter(cell => byCell.has(cell) && cell !== key(entry) && !(inCycle(entry) && inCycle(byCell.get(cell))));
32
+ return { ...entry, formula: precedents[index].formula, origin: inherited.length === 0, inheritedFrom: inherited };
33
+ });
34
+ const summary = result => ({ calculation: result.calculation.status, confirmed: result.assessment.confirmed, unavailable: result.assessment.unavailable, cacheDifferences: result.assessment.cacheDifferences });
35
+ if (!args.fixes?.length) return { mode: 'inspect', before: summary(before), candidates };
36
+
37
+ // All corrections go in one step: while a cycle or an unknown function remains, the workbook cannot be calculated at all.
38
+ const unknown = args.fixes.filter(fix => !byCell.has(key(fix)) && !fix.businessRule);
39
+ if (unknown.length) throw new Error(`These fixes address cells the audit did not flag; mark them businessRule:true if intended: ${unknown.map(key).join(', ')}`);
40
+ const repaired = await wb.run({ operations: args.fixes.map(fix => ({ op: 'write', sheet: fix.sheet, range: fix.cell, values: [[{ formula: fix.formula }]] })) });
41
+ if (!repaired.ok) throw new Error(`Repair failed: ${repaired.error.code} ${repaired.error.message}`);
42
+
43
+ const after = await audit();
44
+ const remaining = after.findings.items.filter(item => item.kind === 'diagnostic');
45
+ if (remaining.length) throw new Error(`Still not clean after the repair: ${remaining.map(item => `${key(item)} ${item.code}`).join(', ')}`);
46
+ const failed = (after.assertions ?? []).filter(item => item.status !== 'passed');
47
+ if (failed.length) throw new Error(`Business rules not satisfied: ${failed.map(item => `${item.id} (${item.status})`).join(', ')}`);
48
+ return { mode: 'repair', before: summary(before), after: summary(after), candidates, fixed: args.fixes.map(key), assertions: (after.assertions ?? []).map(item => ({ id: item.id, status: item.status })) };
@@ -0,0 +1,22 @@
1
+ {
2
+ "input": "sample/model-to-check.xlsx",
3
+ "output": "model-repaired.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "fixes": [
8
+ { "sheet": "模型", "cell": "B3", "formula": "='参数'!C2+1" },
9
+ { "sheet": "模型", "cell": "B4", "formula": "='参数'!B4" },
10
+ { "sheet": "模型", "cell": "B5", "formula": "=B4+1" },
11
+ { "sheet": "模型", "cell": "B6", "formula": "='参数'!B4*11" },
12
+ { "sheet": "模型", "cell": "B10", "formula": "='参数'!C3/'参数'!C2" },
13
+ { "sheet": "模型", "cell": "B1", "formula": "='参数'!$B$2", "businessRule": true },
14
+ { "sheet": "模型", "cell": "B2", "formula": "=SUM('参数'!C2:C4)", "businessRule": true }
15
+ ],
16
+ "assertions": [
17
+ { "id": "tax-binding", "basis": "税率取参数表的税率行", "kind": "references", "sheet": "模型", "cell": "B1", "expected": [{ "sheet": "参数", "range": "B2" }], "mode": "exact" },
18
+ { "id": "complete-sum", "basis": "汇总包含全部三行明细金额 10+20+5", "kind": "value", "sheet": "模型", "cell": "B2", "expected": { "type": "number", "value": 35 } },
19
+ { "id": "quantity-times-eleven", "basis": "数量 7 乘以 11", "kind": "value", "sheet": "模型", "cell": "B6", "expected": { "type": "number", "value": 77 } }
20
+ ]
21
+ }
22
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "source": "scripts/validation/audit.py: the constants BROKEN, REPAIRED and repair_values(), copied by hand. Values follow from the inputs on sheet 参数 (税率 0.13, 明细金额 10/20/5, 数量 7), not from any formula engine.",
3
+ "injectedOrigins": [
4
+ { "cell": "B3", "formula": "=#REF!+1", "code": "BROKEN_REFERENCE" },
5
+ { "cell": "B4", "formula": "=B5", "code": "CIRCULAR_REFERENCE" },
6
+ { "cell": "B5", "formula": "=B4", "code": "CIRCULAR_REFERENCE" },
7
+ { "cell": "B6", "formula": "=MISSING('参数'!B4)", "code": "UNSUPPORTED_FUNCTION" },
8
+ { "cell": "B10", "formula": "=1/0", "code": "FORMULA_ERROR" }
9
+ ],
10
+ "silentBusinessErrors": [
11
+ { "cell": "B1", "formula": "='参数'!$B$3", "intended": "='参数'!$B$2" },
12
+ { "cell": "B2", "formula": "=SUM('参数'!C2:C3)", "intended": "=SUM('参数'!C2:C4)" }
13
+ ],
14
+ "repairedValues": { "B1": 0.13, "C1": 13, "B2": 35, "B3": 11, "C3": 22, "B4": 7, "C4": 8, "B5": 8, "B6": 77, "B7": 77, "B8": 154, "B9": 35, "B10": 2, "C10": 3, "B11": 2 }
15
+ }
@@ -0,0 +1,30 @@
1
+ # 编辑受保护的模型并恢复原有权限
2
+
3
+ 更新无口令保护模型的值或公式、新增汇总表,保存后恢复原有的工作表权限与工作簿结构保护。原本未保护的工作表保持未保护,新增工作表也不自动加保护。
4
+
5
+ 例如交给 agent:“把这份模型的输入改为 12,新增汇总页引用结果;修改后保留原来的保护权限。”agent 将明确获准的修改放进本配方的 `operations`,程序在同一个事务中保存保护状态、解除所需保护、编辑、恢复并核对,最后只发布一次。
6
+
7
+ ## 运行示例
8
+
9
+ 在本目录执行,`excel-kit` 换成当前程序路径:
10
+
11
+ ```sh
12
+ excel-kit run prepare.json
13
+ excel-kit script request.json
14
+ ```
15
+
16
+ 得到 `updated-model.xlsx`:`Inputs!A1=12`,`Inputs!B1` 与 `Summary!B1` 的本次结果均为 24;`Inputs` 仍受保护,原来的选择、列格式、筛选及对象权限保持;结构保护仍生效。`Notes` 与新建的 `Summary` 不受工作表保护。示例源文件由 `prepare.json` 生成,不依赖外部材料。
17
+
18
+ 用于自己的文件时,修改 `request.json` 的 `input`、`output`、`arguments.operations`,保留 `scriptPath`。已知原件摘要时可带 `expectedInputVersion`;已有目标文件沿用公开的 `overwrite.expectedVersion` 规则。
19
+
20
+ ## 参数与失败处理
21
+
22
+ - `operations` 只接受 `write` 和 `sheet.add`。已有工作表身份、单元格锁定及公式隐藏格式保持;改名、删表、格式维护应使用另外制定的完整任务。
23
+ - `calculation` 可指定目标计算,计算不完整默认也接受步骤,须看返回计算状态与诊断文件;要汇总结果全部可得才交付,可在脚本的 wb.run 分组参数上设 requireCompleteCalculation:true;省略时使用 `mode:"none"` 做保存维护,受影响的旧缓存按正常规则清理,不代表整本已计算。
24
+ - 配方只解除本次写入涉及的工作表保护,以及新增工作表所需的结构保护。其他工作表保护不变。
25
+ - 需要解除的保护带口令时,脚本在编辑前失败,说明“请用户在 Excel 中自行解除相应保护并另存副本,再重试”。本配方不接收或猜测口令;现有公开保护操作仍可由有合法口令的用户明确调用。
26
+ - 遇到不支持的扩展保护、编辑失败、整次计算故障或恢复核对失败,配方抛错,源文件及已有目标保持不变,不发布中途解除保护的文件。
27
+
28
+ 恢复时传回查询得到的**完整 `allow`**,不能只写一个无参数 `sheet.protect`,否则会换成新保护的默认权限。工作簿操作仅管理结构锁,原有窗口/修订限制留在原生记录中。`protectedRanges` 及单元格锁定、公式隐藏也由现有保存链保留;配方不修改它们。恢复按权限语义比较,不要求 XML 中 `true/false` 与 `1/0` 的拼写完全一致。
29
+
30
+ 保护操作见 `excel-kit help protection`;脚本什么时候发布见 `SKILL.md` 第 2 条。
@@ -0,0 +1,10 @@
1
+ {
2
+ "create": { "sheets": ["Inputs", "Notes"] },
3
+ "output": "protected-model.xlsx",
4
+ "operations": [
5
+ { "op": "write", "sheet": "Inputs", "range": "A1", "values": [[10, { "formula": "=A1*2" }]] },
6
+ { "op": "format", "sheet": "Inputs", "range": "B1", "style": { "protection": { "locked": true, "hidden": true } } },
7
+ { "op": "sheet.protect", "sheet": "Inputs", "allow": { "selectLockedCells": false, "formatColumns": true, "autoFilter": true, "objects": true } },
8
+ { "op": "workbook.protect" }
9
+ ]
10
+ }
@@ -0,0 +1,41 @@
1
+ // Update values/formulas or add a summary sheet, preserving the original
2
+ // no-password protection permissions. The script publishes only after the
3
+ // restored state has been checked. args: { operations, calculation? }.
4
+ const must = (response, what) => {
5
+ if (!response.ok) {
6
+ const first = response.calculation?.diagnostics?.[0];
7
+ 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})` : ''}`);
8
+ }
9
+ return response;
10
+ };
11
+ const operations = args.operations;
12
+ if (!Array.isArray(operations) || !operations.length || operations.some(op => !op || !['write', 'sheet.add'].includes(op.op))) {
13
+ throw new Error('Provide write and/or sheet.add operations. This recipe preserves existing sheet identities and cell locking.');
14
+ }
15
+ const sheets = must(await wb.inspect(), 'Inspect sheets').workbook.sheets;
16
+ const selections = [{}, ...sheets.map(sheet => ({ sheet: sheet.name }))];
17
+ const before = must(await wb.query({ protection: selections }), 'Read protection').protection;
18
+ const named = name => typeof name === 'string' ? name.toLocaleLowerCase('en-US') : '';
19
+ const written = new Set(operations.filter(op => op.op === 'write').map(op => named(op.sheet)));
20
+ const changedScopes = before.filter(state => state.protected && (state.scope === 'workbook'
21
+ ? operations.some(op => op.op === 'sheet.add') : written.has(named(state.sheet))));
22
+ // Check every required scope before issuing any edit; never guess a password.
23
+ for (const state of changedScopes) {
24
+ const label = state.scope === 'workbook' ? 'Workbook structure' : `Worksheet ${state.sheet}`;
25
+ if (state.password.present) throw new Error(`${label} requires a password. 请用户在 Excel 中自行解除相应保护并另存副本,再用该副本重试;本配方不猜测或移除口令校验。`);
26
+ if (state.unsupportedAttributes.length) throw new Error(`${label} has unsupported protection attributes: ${state.unsupportedAttributes.join(', ')}. No changes were published.`);
27
+ }
28
+ const unlock = changedScopes.map(state => state.scope === 'workbook'
29
+ ? { op: 'workbook.unprotect' } : { op: 'sheet.unprotect', sheet: state.sheet });
30
+ const restore = [...changedScopes].reverse().map(state => state.scope === 'workbook'
31
+ ? { op: 'workbook.protect' } : { op: 'sheet.protect', sheet: state.sheet, allow: state.allow });
32
+ // Unprotect, edit and restore are a single step; even a failure halfway through
33
+ // cannot leave an unlocked version behind. Explicit none preserves formulas
34
+ // without claiming that this maintenance task has calculated the whole model.
35
+ const edited = await wb.run({ operations: [...unlock, ...operations, ...restore], calculation: args.calculation ?? { mode: 'none' } });
36
+ if (!edited.ok) throw new Error(`${edited.error.code}: ${edited.error.message}`);
37
+ const after = must(await wb.query({ protection: selections }), 'Read protection').protection;
38
+ for (let i = 0; i < before.length; i++) {
39
+ if (JSON.stringify(before[i]) !== JSON.stringify(after[i])) throw new Error(`Protection restoration did not match the original state for ${before[i].sheet ?? 'workbook structure'}.`);
40
+ }
41
+ return { operations: operations.length, restored: changedScopes.map(state => state.scope === 'workbook' ? { scope: 'workbook' } : { scope: 'sheet', sheet: state.sheet }), protection: after };
@@ -0,0 +1,14 @@
1
+ {
2
+ "input": "protected-model.xlsx",
3
+ "output": "updated-model.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "operations": [
8
+ { "op": "write", "sheet": "Inputs", "range": "A1", "values": [[12]] },
9
+ { "op": "sheet.add", "name": "Summary" },
10
+ { "op": "write", "sheet": "Summary", "range": "A1", "values": [["Result", { "formula": "=Inputs!B1" }]] }
11
+ ],
12
+ "calculation": { "mode": "targets", "targets": [{ "sheet": "Summary", "range": "B1" }] }
13
+ }
14
+ }
@@ -0,0 +1,30 @@
1
+ # 填写模板、校验、加打印设置与保护
2
+
3
+ 用数据填充 `{{键}}` 占位符并写入原生数字,让模板自带的数据验证规则在发布前判定结果,通过后再加打印设置和工作表保护。
4
+
5
+ ## 运行
6
+
7
+ 在本目录下依次执行:
8
+
9
+ 1. `excel-kit script request.json`:生成 `filled-form.xlsx`。
10
+
11
+ `request.json` 里的路径相对本目录。脚本本体是 `recipe.js`,开头的注释列出了全部参数。
12
+
13
+ ## 参数
14
+
15
+ `data` 是占位符数据(文本);`numbers` 是要写成原生数字的单元格;`validate` 是需要通过验证规则的单元格;`print` 是打印设置;`protect` 是保护选项,可带 `password`。
16
+
17
+ ## 样本与许可
18
+
19
+ `sample/template.xlsx` 由 PowerAI Desktop 的测试样本 `cf-hyperlink-image-protection.xlsx`(Apache-2.0,见 `sample/original/LICENSE`)派生:原件不含占位符和验证规则,且带无口令的工作表保护;派生时用公开操作解除保护、新增"申请单"工作表、写入占位符和四条数据验证规则,派生请求是 `sample/derive-template.request.json`。原件里一张块长度不一致的 2×2 PNG 原样保留,配方不触碰它。
20
+
21
+ ## 样本上的结果
22
+
23
+ 8 个占位符分布在 7 个单元格,全部替换;四个被校验的单元格都通过;金额为 12 × 1350.5 = 16206;工作表受保护并允许调整列宽,打印为 A4 纵向、缩放到一页。
24
+
25
+ ## 要点
26
+
27
+ - 占位符填充只写文本;数字用 `write`,否则数据验证和公式把它当文本。
28
+ - 步骤的 `validate` 让工作簿自己的规则判定:不通过则该步失败,什么都不留下。
29
+ - 数据里缺少某个键按错误处理(`unresolved:"error"`),不会发布还留着 `{{...}}` 的表单。
30
+ - 保护放在最后,避免保护挡住前面的填写。
@@ -0,0 +1,46 @@
1
+ // Fill a structured template, let the workbook's own data-validation rules
2
+ // judge the result before anything is published, then add print settings and
3
+ // protection.
4
+ //
5
+ // args: { sheet, data, numbers?, validate, print?, protect? }
6
+ // sheet the form sheet
7
+ // data JSON object for the {{key}} placeholders (text fields)
8
+ // numbers [{ cell, value }] native numbers; template.fill only writes text
9
+ // validate [range, ...] cells whose validation rules must pass
10
+ // print print.set properties for the sheet
11
+ // protect { allow?, password? } sheet protection to add last
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 { sheet } = args;
20
+ // One step: fill, write the numbers, and have the rules checked. If a rule fails the step fails and nothing of it remains.
21
+ const filled = await wb.run({
22
+ operations: [
23
+ { op: 'template.fill', sheet, data: args.data, unresolved: 'error' },
24
+ ...(args.numbers ?? []).map(item => ({ op: 'write', sheet, range: item.cell, values: [[item.value]] })),
25
+ ],
26
+ validate: args.validate.map(range => ({ sheet, range })),
27
+ }).catch(error => error.response);
28
+ if (!filled.ok) {
29
+ const failures = (filled.error.details?.ranges ?? []).flatMap(range => (range.failures ?? []).map(cell => `${range.sheet}!${cell.cell}`));
30
+ throw new Error(`${filled.error.code}: ${filled.error.message}${failures.length ? ' Cells: ' + failures.join(', ') : ''}`);
31
+ }
32
+
33
+ // Presentation and protection come last, so a protected sheet never blocks the filling above.
34
+ const finished = await wb.run({ operations: [
35
+ ...(args.print ? [{ op: 'print.set', sheet, ...args.print }] : []),
36
+ ...(args.protect ? [{ op: 'sheet.protect', sheet, ...args.protect }] : []),
37
+ ] });
38
+ if (!finished.ok) throw new Error(`${finished.error.code}: ${finished.error.message}`);
39
+
40
+ const template = filled.result.templates[0];
41
+ const state = must(await wb.query({ protection: [{ sheet }], printing: [{ sheet }] }), 'Read presentation');
42
+ return {
43
+ replacements: template.replacements, changedCells: template.changedCells, usedKeys: template.usedKeys, unresolved: template.unresolved.occurrences,
44
+ validation: filled.result.validation.ranges.map(range => ({ range: range.range, ...range.counts })),
45
+ protected: state.protection[0].protected, printAreas: state.printing[0].areas,
46
+ };
@@ -0,0 +1,18 @@
1
+ {
2
+ "input": "sample/template.xlsx",
3
+ "output": "filled-form.xlsx",
4
+ "scriptPath": "recipe.js",
5
+ "strict": true,
6
+ "arguments": {
7
+ "sheet": "申请单",
8
+ "data": {
9
+ "applicant": { "name": "王小明", "department": "工程部", "id": "E-017" },
10
+ "project": { "name": "泵房改造", "code": "PRJ-2026-04" },
11
+ "date": "2026-09-19", "notes": "含备件", "approval": { "comment": "" }
12
+ },
13
+ "numbers": [{ "cell": "B7", "value": 12 }, { "cell": "B8", "value": 1350.5 }],
14
+ "validate": ["B3", "B4", "B7", "B8"],
15
+ "print": { "areas": ["A1:B13"], "orientation": "portrait", "paperSize": 9, "scaling": { "mode": "fit", "width": 1, "height": 1 }, "headerFooter": { "oddFooter": "&C第 &P 页,共 &N 页" } },
16
+ "protect": { "allow": { "formatColumns": true } }
17
+ }
18
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "input": "sample/original/cf-hyperlink-image-protection.xlsx",
3
+ "output": "sample/template.xlsx",
4
+ "operations": [
5
+ { "op": "sheet.unprotect", "sheet": "S" },
6
+ { "op": "sheet.add", "name": "申请单" },
7
+ { "op": "write", "sheet": "申请单", "range": "A1", "values": [
8
+ ["项目申请单", null], [null, null],
9
+ ["申请人", "{{applicant.name}}"], ["部门", "{{applicant.department}}"], ["项目名称", "{{project.name}}"], ["申请日期", "{{date}}"],
10
+ ["数量", null], ["单价", null], ["金额", { "formula": "=B7*B8" }], ["备注", "{{notes}}"],
11
+ [null, null], ["审批意见", "{{approval.comment}}"], ["编号", "{{project.code}}-{{ applicant.id }}"]
12
+ ] },
13
+ { "op": "format", "sheet": "申请单", "range": "A1", "style": { "font": { "bold": true, "size": 14 } } },
14
+ { "op": "format", "sheet": "申请单", "range": "A3:A13", "style": { "font": { "bold": true } } },
15
+ { "op": "format", "sheet": "申请单", "range": "B8:B9", "style": { "numberFormat": "#,##0.00" } },
16
+ { "op": "layout", "sheet": "申请单", "columns": [{ "range": "A", "width": 14 }, { "range": "B", "width": 36 }] },
17
+ { "op": "validation.set", "sheet": "申请单", "ranges": ["B4"], "rule": { "kind": "list", "values": ["工程部", "财务部", "采购部"] }, "error": { "title": "部门", "text": "请选择列表中的部门", "style": "stop" } },
18
+ { "op": "validation.set", "sheet": "申请单", "ranges": ["B7"], "rule": { "kind": "number", "min": 1, "max": 100, "whole": true }, "allowBlank": false },
19
+ { "op": "validation.set", "sheet": "申请单", "ranges": ["B8"], "rule": { "kind": "number", "min": 0, "max": 100000 }, "allowBlank": false },
20
+ { "op": "validation.set", "sheet": "申请单", "ranges": ["B3"], "rule": { "kind": "textLength", "operator": "between", "values": [1, 20] }, "allowBlank": false }
21
+ ]
22
+ }