@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.
- package/CHANGELOG.md +19 -0
- package/DISTRIBUTION.md +13 -0
- package/LICENSE +45 -0
- package/README.md +74 -2
- package/SKILL.md +52 -0
- package/THIRD-PARTY-NOTICES.txt +3050 -0
- package/VALIDATION.md +46 -0
- package/bin/excel-kit.cjs +50 -0
- package/package.json +19 -4
- package/recipes/README.md +31 -0
- package/recipes/audit-and-repair/README.md +30 -0
- package/recipes/audit-and-repair/inspect.json +7 -0
- package/recipes/audit-and-repair/recipe.js +48 -0
- package/recipes/audit-and-repair/request.json +22 -0
- package/recipes/audit-and-repair/sample/clean-control.xlsx +0 -0
- package/recipes/audit-and-repair/sample/expected.json +15 -0
- package/recipes/audit-and-repair/sample/model-to-check.xlsx +0 -0
- package/recipes/edit-protected-workbook/README.md +30 -0
- package/recipes/edit-protected-workbook/prepare.json +10 -0
- package/recipes/edit-protected-workbook/recipe.js +41 -0
- package/recipes/edit-protected-workbook/request.json +14 -0
- package/recipes/fill-template/README.md +30 -0
- package/recipes/fill-template/recipe.js +46 -0
- package/recipes/fill-template/request.json +18 -0
- package/recipes/fill-template/sample/derive-template.request.json +22 -0
- package/recipes/fill-template/sample/original/LICENSE +201 -0
- package/recipes/fill-template/sample/original/cf-hyperlink-image-protection.xlsx +0 -0
- package/recipes/fill-template/sample/template.xlsx +0 -0
- package/recipes/import-clean-append/README.md +30 -0
- package/recipes/import-clean-append/prepare.json +8 -0
- package/recipes/import-clean-append/recipe.js +77 -0
- package/recipes/import-clean-append/request.json +22 -0
- package/recipes/import-clean-append/sample/incoming-1.csv +4 -0
- package/recipes/import-clean-append/sample/incoming-2.csv +3 -0
- package/recipes/import-clean-append/sample/trading-table.xlsx +0 -0
- package/recipes/inventory-media/README.md +31 -0
- package/recipes/inventory-media/prepare.json +9 -0
- package/recipes/inventory-media/recipe.js +44 -0
- package/recipes/inventory-media/request.json +7 -0
- package/recipes/inventory-media/sample/LICENSE +268 -0
- package/recipes/inventory-media/sample/NOTICE +36 -0
- package/recipes/inventory-media/sample/WithEmbeded.xlsx +0 -0
- package/recipes/inventory-media/sample/blue.png +0 -0
- package/recipes/inventory-media/sample/green.jpg +0 -0
- package/recipes/normalize-codes/README.md +30 -0
- package/recipes/normalize-codes/prepare.json +73 -0
- package/recipes/normalize-codes/recipe.js +34 -0
- package/recipes/normalize-codes/request.json +7 -0
- package/recipes/normalize-codes/sample/trading-table.xlsx +0 -0
- package/recipes/pivot-by-slicer/README.md +30 -0
- package/recipes/pivot-by-slicer/prepare.json +11 -0
- package/recipes/pivot-by-slicer/recipe.js +34 -0
- package/recipes/pivot-by-slicer/request.json +14 -0
- package/recipes/repair-and-test-model/README.md +13 -0
- package/recipes/repair-and-test-model/workflow.py +108 -0
- package/recipes/roll-forward-period/README.md +30 -0
- package/recipes/roll-forward-period/prepare.json +10 -0
- package/recipes/roll-forward-period/recipe.js +49 -0
- package/recipes/roll-forward-period/request.json +13 -0
- package/recipes/roll-forward-period/sample/budget-template.xlsx +0 -0
- package/recipes/style-matching-sheets/README.md +28 -0
- package/recipes/style-matching-sheets/recipe.js +38 -0
- package/recipes/style-matching-sheets/request.json +17 -0
- package/recipes/style-matching-sheets/sample/build-workbook.request.json +13 -0
- package/recipes/style-matching-sheets/sample/report-tables.xlsx +0 -0
- package/recipes/update-assumptions/README.md +29 -0
- package/recipes/update-assumptions/recipe.js +66 -0
- package/recipes/update-assumptions/request.json +10 -0
- package/recipes/update-assumptions/sample/build-model.request.json +12 -0
- package/recipes/update-assumptions/sample/cost-model.xlsx +0 -0
- package/recipes/update-matching-records/README.md +35 -0
- package/recipes/update-matching-records/incomplete-strict.json +33 -0
- package/recipes/update-matching-records/incomplete.json +32 -0
- package/recipes/update-matching-records/prepare-incomplete.json +21 -0
- package/recipes/update-matching-records/recipe.js +35 -0
- package/recipes/update-matching-records/request.json +29 -0
- package/recipes/update-matching-records/sample/trading-table.xlsx +0 -0
- package/reference/api.md +59 -0
- package/reference/audit.md +50 -0
- package/reference/calculation.md +82 -0
- package/reference/cost.md +61 -0
- package/reference/deliverable.md +66 -0
- package/reference/editing-and-saving.md +69 -0
- package/reference/errors.md +65 -0
- package/reference/external-links.md +39 -0
- package/reference/function-limits.md +30 -0
- package/reference/paging.md +63 -0
- package/reference/pivots.md +46 -0
- package/reference/presentation.md +11 -0
- package/reference/protection.md +63 -0
- package/reference/reading.md +70 -0
- package/reference/scripts.md +74 -0
- package/reference/selection.md +43 -0
- package/reference/session-loop.md +62 -0
- package/reference/sessions.md +54 -0
- package/reference/unsupported.md +31 -0
- package/release.json +41 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Run in an empty output directory. Python orchestrates the public ExcelKit CLI."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import subprocess
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(directory, cli):
|
|
9
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
10
|
+
source, baseline, working, delivery = [str(directory / (name + ".xlsx"))
|
|
11
|
+
for name in ("source", "baseline", "working", "delivery")]
|
|
12
|
+
|
|
13
|
+
def invoke(command, request):
|
|
14
|
+
p = subprocess.run([*cli, command, "-"], input=json.dumps(request), text=True, capture_output=True)
|
|
15
|
+
result = json.loads(p.stdout)
|
|
16
|
+
if not result["ok"]:
|
|
17
|
+
raise RuntimeError(result)
|
|
18
|
+
return result
|
|
19
|
+
|
|
20
|
+
def write(sheet, cell, *rows):
|
|
21
|
+
return dict(op="write", sheet=sheet, range=cell, values=rows)
|
|
22
|
+
|
|
23
|
+
def formula(text):
|
|
24
|
+
return {"formula": "=" + text}
|
|
25
|
+
|
|
26
|
+
def name(sheet, address):
|
|
27
|
+
return dict(op="name.set", name="Rate", reference=sheet + "!" + address)
|
|
28
|
+
|
|
29
|
+
chart = dict(op="chart.create", sheet="Model", name="Charges", type="column",
|
|
30
|
+
series=[dict(categories="Model!A2:A3", values="Model!C2:C3")],
|
|
31
|
+
anchor=dict(kind="oneCell", **{"from": {"cell": "F2"}}, width=260, height=140))
|
|
32
|
+
original = invoke("run", dict(create=dict(sheets=["Model"]), output=source, operations=[
|
|
33
|
+
write("Model", "A1", ["Review\ncharges\nby region"]),
|
|
34
|
+
dict(op="merge", sheet="Model", range="A1:C1"),
|
|
35
|
+
dict(op="format", sheet="Model", range="A1", style=dict(alignment=dict(wrapText=True),font=dict(bold=True))),
|
|
36
|
+
write("Model", "A2", [10,2,formula("A2*B2*Rate")],[7,3,formula("$A2+A$2+$A$2")]),
|
|
37
|
+
write("Model", "H1", [4]), name("Model","$H$1"),chart]))
|
|
38
|
+
invoke("run",dict(create=dict(sheets=["Model","Data","Summary"]), output=baseline, operations=[
|
|
39
|
+
write("Model","A2",[5,None,4]),write("Model","A6",[3]), write("Model","B1",[1.5]),name("Model","$B$1"),
|
|
40
|
+
write("Model","E6",[formula("C6*D6*Rate")]), write("Model","C6",[10,2]),
|
|
41
|
+
dict(op="layout",sheet="Model",rows=[dict(start=5,count=1,height=15)]),
|
|
42
|
+
write("Data","A1",["Region","Cost","Qty"],["East",-1.25,1],["East",-1.20,1],["West",3,0]),
|
|
43
|
+
dict(op="table.create",sheet="Data",name="Inputs",range="A1:C4")]))
|
|
44
|
+
broken = invoke("run",dict(input=baseline,output=working,operations=[write("Model","E6",[30])]))
|
|
45
|
+
difference = invoke("compare",dict(left=baseline,right=working,sheet="Model",range="C5:E7"))
|
|
46
|
+
assert difference["total"] == 1 and difference["items"][0]["left"]["content"]["type"] == "formula", difference
|
|
47
|
+
|
|
48
|
+
# A receiving session can contain other work before the repair starts.
|
|
49
|
+
with subprocess.Popen([*cli,"session"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,text=True) as proc:
|
|
50
|
+
seq = 0
|
|
51
|
+
def rpc(method, **params):
|
|
52
|
+
nonlocal seq
|
|
53
|
+
seq += 1
|
|
54
|
+
message = dict(jsonrpc="2.0",id=seq,method="session."+method,params=dict(sessionId="model",**params))
|
|
55
|
+
proc.stdin.write(json.dumps(message) + "\n")
|
|
56
|
+
proc.stdin.flush()
|
|
57
|
+
response = json.loads(proc.stdout.readline())["result"]["response"]
|
|
58
|
+
if not response["ok"]:
|
|
59
|
+
raise RuntimeError(response)
|
|
60
|
+
return response
|
|
61
|
+
|
|
62
|
+
rpc("open",input=working,output=delivery,expectedInputVersion=broken["output"]["version"],reread="precise")
|
|
63
|
+
edit = rpc("run",**write("Summary","A9",["Reviewed"]))
|
|
64
|
+
version = edit["outputVersion"]
|
|
65
|
+
move = dict(op="range.transfer",sheet="Model",cell="C5",chart="Charges",
|
|
66
|
+
source=dict(path=source,sheet="Model",range="A1:C3",expectedVersion=original["output"]["version"]),
|
|
67
|
+
bindings=[dict(**{"from":"Rate","to":"Rate"})],replaceRange="C5:E7",expectedTargetVersion=version)
|
|
68
|
+
move_script = "const step = await wb.run(args.move); return step.result.rangeOperations[0].transfer;"
|
|
69
|
+
# The exact replacement can be tried against the current unsaved model.
|
|
70
|
+
plan = rpc("script",expectedSessionVersion=version,trial=True,strict=True,script=move_script,arguments={"move":move})
|
|
71
|
+
assert plan["outputVersion"] == version
|
|
72
|
+
rpc("run",expectedSessionVersion=version,**move)
|
|
73
|
+
scenario = """
|
|
74
|
+
const step = await wb.run({operations:[{op:"write",sheet:"Model",range:"C6",values:[[args.units]]}],
|
|
75
|
+
calculation:{mode:"targets",targets:[{sheet:"Model",range:"E6"}]},read:[{sheet:"Model",range:"E6"}]});
|
|
76
|
+
return step.result.ranges[0].cells[0][0].result.value;
|
|
77
|
+
"""
|
|
78
|
+
values = [rpc("script",trial=True,strict=True,script=scenario,arguments=dict(units=n))["result"] for n in (12,18)]
|
|
79
|
+
assert values == [36,54], values
|
|
80
|
+
chosen = rpc("script",strict=True,script=scenario,arguments=dict(units=12))
|
|
81
|
+
assert chosen["result"] == 36
|
|
82
|
+
rpc("run",op="pivot.create",sheet="Summary",cell="A1",name="Costs",source="Inputs",rows=["Region"],
|
|
83
|
+
calculatedFields=[dict(name="UnitCost",formula="IF(Qty=0,0,ROUND(ABS(Cost/Qty),2))")],
|
|
84
|
+
values=[dict(field="UnitCost",name="Unit cost")])
|
|
85
|
+
rpc("run",operations=[write("Data","B2",[-1.27]),dict(op="pivot.refresh",sheet="Summary",name="Costs"),
|
|
86
|
+
dict(op="chart.refresh",sheet="Model",name="Charges")])
|
|
87
|
+
layout = dict(sheet="Model",range="C5:E5",axis="textClipping")
|
|
88
|
+
clipped = rpc("query",layout=[layout])["layout"][0]["items"]
|
|
89
|
+
assert len(clipped) == 1 and clipped[0]["range"] == "C5:E5", clipped
|
|
90
|
+
rpc("run",op="layout",sheet="Model",rows=[dict(start=5,count=1,height=70)])
|
|
91
|
+
assert rpc("query",layout=[layout])["layout"][0]["total"] == 0
|
|
92
|
+
final = rpc("read",ranges=[dict(sheet="Model",range="E6:E7"),dict(sheet="Summary",range="B2:B4")],calculation=dict(mode="all"))
|
|
93
|
+
values_seen = [[r[0]["result"]["value"] if r[0].get("result") else r[0]["input"]["value"] for r in area["cells"]] for area in final["ranges"]]
|
|
94
|
+
assert values_seen == [[36,12],[1.24,0,0.27]], values_seen
|
|
95
|
+
receipt = rpc("save")
|
|
96
|
+
rpc("close")
|
|
97
|
+
proc.stdin.close()
|
|
98
|
+
report = dict(changedCell=difference["items"][0],transfer=plan["result"],scenarios=values,selectedUnits=12,
|
|
99
|
+
committedCharge=chosen["result"],reread=chosen["reread"],clipping=clipped,pivotAndFormulaValues=values_seen,output=receipt["output"])
|
|
100
|
+
(directory/"report.json").write_text(json.dumps(report,indent=2)+"\n")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
parser=argparse.ArgumentParser(description=__doc__)
|
|
105
|
+
parser.add_argument("directory",type=Path)
|
|
106
|
+
parser.add_argument("--cli",nargs="+",default=["excel-kit"])
|
|
107
|
+
args=parser.parse_args()
|
|
108
|
+
main(args.directory.resolve(),args.cli)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# 滚动到下一期间
|
|
2
|
+
|
|
3
|
+
复制最新的期间工作表,填入新期间数据,修改共用假设,在汇总表登记新期间,然后刷新工作簿里全部图表、迷你图与透视,使它们不再显示旧数。
|
|
4
|
+
|
|
5
|
+
## 运行
|
|
6
|
+
|
|
7
|
+
在本目录下依次执行:
|
|
8
|
+
|
|
9
|
+
1. `excel-kit run prepare.json`:在预算模板上加一个图表、一组迷你图和一个透视,生成 `sample/budget-with-objects.xlsx`。
|
|
10
|
+
2. `excel-kit script request.json`:生成 `budget-2026-02.xlsx`。
|
|
11
|
+
|
|
12
|
+
`request.json` 里的路径相对本目录。脚本本体是 `recipe.js`,开头的注释列出了全部参数。
|
|
13
|
+
|
|
14
|
+
## 参数
|
|
15
|
+
|
|
16
|
+
`source`、`target` 是被复制与新建的工作表;`updates` 写到新表;`assumptions` 是共用输入;`summary` 是汇总表新增的一行,可含公式。
|
|
17
|
+
|
|
18
|
+
## 样本与许可
|
|
19
|
+
|
|
20
|
+
`sample/budget-template.xlsx` 是本仓库第三阶段用 XlsxWriter 合成的预算模板,不是第三方文件,可再分发。模板自带的图表引用固定数据,所以图表、迷你图与透视由 `prepare.json` 用公开操作加上,来源指向期间区块。
|
|
21
|
+
|
|
22
|
+
## 样本上的结果
|
|
23
|
+
|
|
24
|
+
新期间数量 5、1、10,税率由 9% 改为 10%:新表不含税金额 62.5、20、52.5,合计 135,税额合计 13.5;原期间税额变为 3.75、4、2.1;透视随之重建;两张期间表的图表缓存分别是各自的金额。
|
|
25
|
+
|
|
26
|
+
## 要点
|
|
27
|
+
|
|
28
|
+
- 来源发生变化的透视必须在改动它的同一步里刷新,否则该步以 `PIVOT_REFRESH_REQUIRED` 失败。配方因此先清点透视,再把刷新与编辑放在同一步。
|
|
29
|
+
- 目标工作表已存在时拒绝执行,避免重复滚动。
|
|
30
|
+
- 工作表复制会带上图表、迷你图、打印设置和表内名称;Table 与透视不随表复制。
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"input": "sample/budget-template.xlsx",
|
|
3
|
+
"output": "sample/budget-with-objects.xlsx",
|
|
4
|
+
"operations": [
|
|
5
|
+
{ "op": "chart.create", "sheet": "2026 01", "name": "本期构成", "type": "column", "anchor": { "kind": "oneCell", "from": { "cell": "H3" }, "width": 360, "height": 220 }, "title": "不含税金额", "series": [{ "name": "不含税", "categories": "'2026 01'!$A$4:$A$6", "values": "'2026 01'!$D$4:$D$6" }] },
|
|
6
|
+
{ "op": "sparkline.create", "sheet": "2026 01", "type": "column", "members": [{ "cell": "G8", "source": "'2026 01'!D4:D6" }] },
|
|
7
|
+
{ "op": "sheet.add", "name": "透视" },
|
|
8
|
+
{ "op": "pivot.create", "sheet": "透视", "name": "税额汇总", "cell": "A3", "source": "'2026 01'!$A$3:$F$6", "rows": ["项目"], "values": [{ "field": "税额", "aggregate": "sum", "name": "税额合计" }], "grandTotalCaption": "总计" }
|
|
9
|
+
]
|
|
10
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Roll a period workbook forward: copy the latest period sheet, enter the new
|
|
2
|
+
// period's figures, change shared assumptions, add the period to the summary,
|
|
3
|
+
// then refresh every chart, sparkline group and pivot in the workbook so none
|
|
4
|
+
// of them shows stale numbers.
|
|
5
|
+
//
|
|
6
|
+
// args: { source, target, updates?, assumptions?, summary? }
|
|
7
|
+
// source period sheet to copy; target: name of the new sheet
|
|
8
|
+
// updates [{ cell, value }] written on the new sheet
|
|
9
|
+
// assumptions [{ sheet, cell, value }] shared inputs to change
|
|
10
|
+
// summary { sheet, range, values } a row to add to the summary (values may hold formulas)
|
|
11
|
+
const must = (response, what) => {
|
|
12
|
+
if (!response.ok) {
|
|
13
|
+
const first = response.calculation?.diagnostics?.[0];
|
|
14
|
+
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})` : ''}`);
|
|
15
|
+
}
|
|
16
|
+
return response;
|
|
17
|
+
};
|
|
18
|
+
const names = must(await wb.inspect(), 'Inspect').workbook.sheets.map(sheet => sheet.name);
|
|
19
|
+
if (!names.includes(args.source)) throw new Error(`Source sheet ${args.source} not found.`);
|
|
20
|
+
if (names.includes(args.target)) throw new Error(`Sheet ${args.target} already exists; this period was rolled forward before.`);
|
|
21
|
+
|
|
22
|
+
// 1. Copy and edit in one step. The copy brings its chart, sparklines, print settings and sheet-local names, retargeted to the new sheet.
|
|
23
|
+
// Pivots whose source changes must be refreshed in the step that changes it, so the existing pivots are listed first and refreshed here.
|
|
24
|
+
const listed = must(await wb.query({ pivots: names.map(sheet => ({ sheet })) }), 'List pivots');
|
|
25
|
+
const pivots = listed.pivots.flatMap(page => page.items.map(item => ({ sheet: page.sheet, name: item.name })));
|
|
26
|
+
must(await wb.run({ id: 'roll-forward', operations: [
|
|
27
|
+
{ op: 'sheet.copy', sheet: args.source, name: args.target },
|
|
28
|
+
...(args.updates ?? []).map(item => ({ op: 'write', sheet: args.target, range: item.cell, values: [[item.value]] })),
|
|
29
|
+
...(args.assumptions ?? []).map(item => ({ op: 'write', sheet: item.sheet, range: item.cell, values: [[item.value]] })),
|
|
30
|
+
...(args.summary ? [{ op: 'write', sheet: args.summary.sheet, range: args.summary.range, values: args.summary.values }] : []),
|
|
31
|
+
...pivots.map(item => ({ op: 'pivot.refresh', ...item })),
|
|
32
|
+
] }), 'Roll forward');
|
|
33
|
+
|
|
34
|
+
// 2. Charts and sparklines cache their points. List them on every sheet, the new one included, and refresh them all in one step.
|
|
35
|
+
const sheets = must(await wb.inspect(), 'Inspect').workbook.sheets.map(sheet => sheet.name);
|
|
36
|
+
const found = must(await wb.query({ charts: sheets.map(sheet => ({ sheet })), sparklines: sheets.map(sheet => ({ sheet })) }), 'List objects');
|
|
37
|
+
const charts = found.charts.flatMap(page => page.items.map(item => ({ sheet: page.sheet, name: item.name })));
|
|
38
|
+
const sparklines = found.sparklines.flatMap(page => page.items.map(item => ({ sheet: page.sheet, index: item.index })));
|
|
39
|
+
must(await wb.run({ id: 'refresh-objects', operations: [
|
|
40
|
+
...charts.map(item => ({ op: 'chart.refresh', ...item })),
|
|
41
|
+
...sparklines.map(item => ({ op: 'sparkline.refresh', ...item })),
|
|
42
|
+
] }), 'Refresh');
|
|
43
|
+
|
|
44
|
+
// 3. Report what the refreshed objects now hold.
|
|
45
|
+
const after = must(await wb.query({ charts: [...new Set(charts.map(item => item.sheet))].map(sheet => ({ sheet })), pivots: [...new Set(pivots.map(item => item.sheet))].map(sheet => ({ sheet })) }), 'Read refreshed objects');
|
|
46
|
+
const chartValues = after.charts.flatMap(page => page.items.map(item => ({ sheet: page.sheet, name: item.name,
|
|
47
|
+
values: item.series.map(series => (series.sources.find(source => source.role === 'val').cache?.points ?? []).map(point => Number(point.value))) })));
|
|
48
|
+
return { copied: { from: args.source, to: args.target }, refreshed: { charts: charts.length, sparklines: sparklines.length, pivots: pivots.length }, charts: chartValues,
|
|
49
|
+
pivots: after.pivots.flatMap(page => page.items.map(item => ({ sheet: page.sheet, name: item.name, state: item.state ?? null }))) };
|
|
@@ -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
|
+
}
|
|
Binary file
|
|
@@ -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
|
+
}
|
|
Binary file
|
|
@@ -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
|
+
}
|
|
Binary file
|
|
@@ -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
|
+
};
|