@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.
- package/CHANGELOG.md +12 -0
- package/DISTRIBUTION.md +13 -0
- package/LICENSE +45 -0
- package/README.md +74 -2
- package/SKILL.md +101 -0
- package/THIRD-PARTY-NOTICES.txt +3050 -0
- package/VALIDATION.md +39 -0
- package/bin/excel-kit.cjs +50 -0
- package/package.json +19 -4
- package/recipes/README.md +29 -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/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 +67 -0
- package/reference/external-links.md +35 -0
- package/reference/function-limits.md +30 -0
- package/reference/paging.md +59 -0
- package/reference/pivots.md +40 -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 +48 -0
- package/reference/unsupported.md +31 -0
- package/release.json +41 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 PowerAI (powerai.com)
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
Binary file
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# 导入 CSV、清洗、去重并追加到 Table
|
|
2
|
+
|
|
3
|
+
把多个 CSV 按类型导入暂存表,在脚本里清洗与映射字段,剔除不完整记录,对文件内和 Table 内已有的记录去重,追加到带活动筛选的 Table,重应用筛选,最后用独立求和核对可见小计。
|
|
4
|
+
|
|
5
|
+
## 运行
|
|
6
|
+
|
|
7
|
+
在本目录下依次执行:
|
|
8
|
+
|
|
9
|
+
1. `excel-kit run prepare.json`:给样本 Table 加上筛选条件(数量不小于 2)和一个 SUBTOTAL 单元格,生成 `sample/filtered-table.xlsx`。
|
|
10
|
+
2. `excel-kit script request.json`:生成 `table-with-imports.xlsx`。
|
|
11
|
+
|
|
12
|
+
`request.json` 里的路径相对本目录。脚本本体是 `recipe.js`,开头的注释列出了全部参数。
|
|
13
|
+
|
|
14
|
+
## 参数
|
|
15
|
+
|
|
16
|
+
`sources` 是 CSV 文件;`columns` 是导入时的列类型;`map` 把 CSV 列映射到 Table 列,可带 `trim`、`pattern`、`replacement`;`key` 是去重键;`required` 是清洗后不能为空的列;`check` 指向 SUBTOTAL 单元格和它汇总的列。
|
|
17
|
+
|
|
18
|
+
## 样本与许可
|
|
19
|
+
|
|
20
|
+
三个样本文件都是本仓库第三阶段合成的,可再分发。样本 Table 原本没有筛选和 SUBTOTAL,由 `prepare.json` 预置。
|
|
21
|
+
|
|
22
|
+
## 样本上的结果
|
|
23
|
+
|
|
24
|
+
5 条 CSV 记录里追加 0004 和 0005;文件内重复 1 条、Table 内已有 1 条、缺单价被拒 1 条;追加后可见 4 行,可见小计 95.75。
|
|
25
|
+
|
|
26
|
+
## 要点
|
|
27
|
+
|
|
28
|
+
- 脚本不能直接读文件。CSV 先用 `data` 操作按类型导入暂存表,脚本读回后在代码里清洗,最后在同一步里删除暂存表。
|
|
29
|
+
- 日期和数字由导入按声明的格式解析,脚本不猜格式。
|
|
30
|
+
- 向带活动筛选的 Table 追加,必须在同一步里 `filter.reapply`。
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"input": "sample/trading-table.xlsx",
|
|
3
|
+
"output": "sample/filtered-table.xlsx",
|
|
4
|
+
"operations": [
|
|
5
|
+
{ "op": "filter.set", "target": { "table": "交易明细" }, "columns": [{ "column": "数量", "condition": { "kind": "number", "comparisons": [{ "operator": "greaterThanOrEqual", "value": 2 }] } }] },
|
|
6
|
+
{ "op": "write", "sheet": "月汇总", "range": "D1", "values": [["可见金额合计", { "formula": "=SUBTOTAL(109,交易明细[金额])" }]] }
|
|
7
|
+
]
|
|
8
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Import CSV files, clean and map their columns, drop duplicates, append the
|
|
2
|
+
// rest to a Table that has an active filter, reapply the filter and check the
|
|
3
|
+
// visible subtotal against an independent sum.
|
|
4
|
+
//
|
|
5
|
+
// args: { table, sources, columns, map, key, required, check }
|
|
6
|
+
// table Table to append to
|
|
7
|
+
// sources [{ csv, delimiter? }] files to import, in order
|
|
8
|
+
// columns typed CSV columns for the import, e.g. { name: '日期文本', type: 'date', format: 'YYYY-MM-DD' }
|
|
9
|
+
// map { <Table column>: { from: <CSV column>, trim?, pattern?, replacement? } }
|
|
10
|
+
// key Table column that identifies a record
|
|
11
|
+
// required Table columns that must not be empty after cleaning
|
|
12
|
+
// check { sheet, cell, column } a SUBTOTAL cell and the Table column it sums over visible rows
|
|
13
|
+
const must = (response, what) => {
|
|
14
|
+
if (!response.ok) {
|
|
15
|
+
const first = response.calculation?.diagnostics?.[0];
|
|
16
|
+
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})` : ''}`);
|
|
17
|
+
}
|
|
18
|
+
return response;
|
|
19
|
+
};
|
|
20
|
+
const plain = range => range.cells.map(row => row.map(cell => cell.result?.value ?? null));
|
|
21
|
+
|
|
22
|
+
// 1. Stage every CSV on its own temporary sheet with typed columns. Dates and numbers are parsed by the import, never guessed.
|
|
23
|
+
const staging = args.sources.map((_, index) => `_import_${index + 1}`);
|
|
24
|
+
const staged = await wb.run({ operations: args.sources.flatMap((source, index) => [
|
|
25
|
+
{ op: 'sheet.add', name: staging[index] },
|
|
26
|
+
{ op: 'data', id: `source${index + 1}`, sheet: staging[index], range: 'A1', sources: [{ id: 'csv', csv: source.csv, delimiter: source.delimiter ?? ',', header: true }], columns: args.columns, steps: [] },
|
|
27
|
+
]) });
|
|
28
|
+
must(staged, 'Import failed');
|
|
29
|
+
|
|
30
|
+
// 2. Read the staged rows back and clean them here, in code.
|
|
31
|
+
const read = must(await wb.read({ ranges: staged.result.data.map(data => ({ sheet: data.destination.sheet, range: data.destination.range })) }), 'Read imports');
|
|
32
|
+
const clean = (value, rule) => {
|
|
33
|
+
if (typeof value !== 'string') return value;
|
|
34
|
+
let text = rule.trim ? value.trim().replace(/\s+/g, ' ') : value;
|
|
35
|
+
if (rule.pattern) { const pattern = new RegExp(rule.pattern); if (!pattern.test(text)) return null; text = text.replace(pattern, rule.replacement ?? '$&'); }
|
|
36
|
+
return text;
|
|
37
|
+
};
|
|
38
|
+
const records = [];
|
|
39
|
+
for (const [index, range] of read.ranges.entries()) {
|
|
40
|
+
const [header, ...rows] = plain(range);
|
|
41
|
+
for (const [offset, row] of rows.entries()) {
|
|
42
|
+
const source = Object.fromEntries(header.map((name, column) => [name, row[column]]));
|
|
43
|
+
const record = Object.fromEntries(Object.entries(args.map).map(([column, rule]) => [column, clean(source[rule.from], rule)]));
|
|
44
|
+
records.push({ record, origin: `${args.sources[index].csv} row ${offset + 2}` });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 3. Reject incomplete records, then drop duplicates: within the files (first wins) and against the Table.
|
|
49
|
+
const table = must(await wb.inspect(), 'Inspect table').workbook.tables.find(item => item.name === args.table);
|
|
50
|
+
if (!table) throw new Error(`Table ${args.table} not found.`);
|
|
51
|
+
const names = table.columns.map(column => column.name);
|
|
52
|
+
const body = plain(must(await wb.read({ ranges: [{ sheet: table.sheet, range: table.range }] }), 'Read table').ranges[0]).slice(1);
|
|
53
|
+
const seen = new Set(body.map(row => row[names.indexOf(args.key)]));
|
|
54
|
+
const accepted = [], rejected = [], duplicates = [];
|
|
55
|
+
for (const { record, origin } of records) {
|
|
56
|
+
const missing = args.required.filter(column => record[column] === null || record[column] === undefined || record[column] === '');
|
|
57
|
+
if (missing.length) { rejected.push({ origin, missing }); continue; }
|
|
58
|
+
if (seen.has(record[args.key])) { duplicates.push({ origin, key: record[args.key] }); continue; }
|
|
59
|
+
seen.add(record[args.key]); accepted.push(record);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 4. One step: drop the staging sheets, append, and reapply the Table's filter. Appending under an active filter requires the reapply in the same step.
|
|
63
|
+
const columns = Object.keys(args.map);
|
|
64
|
+
const appended = await wb.run({ operations: [
|
|
65
|
+
...staging.map(sheet => ({ op: 'sheet.delete', sheet })),
|
|
66
|
+
...(accepted.length ? [{ op: 'table.append', table: args.table, columns, values: accepted.map(record => columns.map(column => record[column])) }, { op: 'filter.reapply', target: { table: args.table } }] : []),
|
|
67
|
+
] });
|
|
68
|
+
must(appended, 'Append failed');
|
|
69
|
+
|
|
70
|
+
// 5. Check the subtotal: recalculate, then add up the visible rows independently.
|
|
71
|
+
const grown = must(await wb.inspect(), 'Inspect table').workbook.tables.find(item => item.name === args.table);
|
|
72
|
+
const after = must(await wb.read({ ranges: [{ sheet: args.check.sheet, range: args.check.cell }, { sheet: grown.sheet, range: grown.range }], calculation: { mode: 'all' } }), 'Read subtotal');
|
|
73
|
+
const subtotal = after.ranges[0].cells[0][0].result?.value ?? null, amount = names.indexOf(args.check.column);
|
|
74
|
+
const visible = after.ranges[1].cells.slice(1).filter(row => row[0].rowVisibility === 'visible');
|
|
75
|
+
const expected = visible.reduce((sum, row) => sum + row[amount].result.value, 0);
|
|
76
|
+
if (Math.abs(subtotal - expected) > 1e-9) throw new Error(`Subtotal ${subtotal} differs from the visible rows' sum ${expected}.`);
|
|
77
|
+
return { imported: records.length, appended: accepted.map(record => record[args.key]), duplicates, rejected, rows: after.ranges[1].cells.length - 1, visibleRows: visible.length, subtotal };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"input": "sample/filtered-table.xlsx",
|
|
3
|
+
"output": "table-with-imports.xlsx",
|
|
4
|
+
"scriptPath": "recipe.js",
|
|
5
|
+
"strict": true,
|
|
6
|
+
"arguments": {
|
|
7
|
+
"table": "交易明细",
|
|
8
|
+
"sources": [{ "csv": "sample/incoming-1.csv" }, { "csv": "sample/incoming-2.csv" }],
|
|
9
|
+
"columns": [
|
|
10
|
+
{ "name": "行号", "type": "text" }, { "name": "原编号", "type": "text" }, { "name": "原名称", "type": "text" },
|
|
11
|
+
{ "name": "日期文本", "type": "date", "format": "YYYY-MM-DD" }, { "name": "数量", "type": "number" }, { "name": "单价", "type": "number", "empty": "null" }
|
|
12
|
+
],
|
|
13
|
+
"map": {
|
|
14
|
+
"编号": { "from": "原编号", "pattern": "^SKU-(\\d{4})-X$", "replacement": "$1" },
|
|
15
|
+
"名称": { "from": "原名称", "trim": true },
|
|
16
|
+
"日期": { "from": "日期文本" }, "数量": { "from": "数量" }, "单价": { "from": "单价" }
|
|
17
|
+
},
|
|
18
|
+
"key": "编号",
|
|
19
|
+
"required": ["编号", "名称", "日期", "数量", "单价"],
|
|
20
|
+
"check": { "sheet": "月汇总", "cell": "E1", "column": "金额" }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# 清点图片与附件并提取核对
|
|
2
|
+
|
|
3
|
+
列出工作簿里每张图片和每个嵌入附件的大小与 SHA-256,并为每一项返回一份可直接执行的提取请求;提取由 `image-extract` 与 `attachment-extract` 命令完成,提取结果的 `output.version` 应等于清单里的 `sha256`。
|
|
4
|
+
|
|
5
|
+
## 运行
|
|
6
|
+
|
|
7
|
+
在本目录下依次执行:
|
|
8
|
+
|
|
9
|
+
1. `excel-kit run prepare.json`:向附件样本插入两张图片,生成 `sample/with-media.xlsx`。
|
|
10
|
+
2. `excel-kit script request.json`:返回清单;脚本只读,不写文件。
|
|
11
|
+
3. 先建 `extracted` 目录,再把清单里每一项的 `extract.request` 存成文件,用 `extract.command` 指明的命令执行。
|
|
12
|
+
|
|
13
|
+
`request.json` 里的路径相对本目录。脚本本体是 `recipe.js`,开头的注释列出了全部参数。
|
|
14
|
+
|
|
15
|
+
## 参数
|
|
16
|
+
|
|
17
|
+
`workbook` 是提取命令要读的工作簿路径;`folder` 是提取文件的目录。
|
|
18
|
+
|
|
19
|
+
## 样本与许可
|
|
20
|
+
|
|
21
|
+
`sample/WithEmbeded.xlsx` 原样取自 Apache POI 的 `test-data/spreadsheet`(Apache-2.0,见 `sample/LICENSE` 与 `sample/NOTICE`)。它不含浮动图片,两张图片由 `prepare.json` 插入:`sample/green.jpg` 是本仓库用 Pillow 生成的纯色 JPEG,`sample/blue.png` 是本仓库用 Python 标准库生成的纯色 PNG,均无外部素材。
|
|
22
|
+
|
|
23
|
+
## 样本上的结果
|
|
24
|
+
|
|
25
|
+
2 张图片(JPEG 637 字节、PNG 78 字节)和 2 个附件(一个 32,768 字节的 XLS 复合文档、一个 1,693 字节的 Ole10Native 压缩包);提取出的文件摘要与清单逐项相等。
|
|
26
|
+
|
|
27
|
+
## 要点
|
|
28
|
+
|
|
29
|
+
- 脚本除工作簿外不能写文件,所以清单与提取分两段:脚本给出请求,一次性命令执行。
|
|
30
|
+
- 附件里存的文件名只是数据,不当作路径:输出名由工作表序号和对象 id 生成,只保留短的字母数字扩展名。
|
|
31
|
+
- 只读脚本仍要在请求里写 `output`,但不会写出任何文件。
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"input": "sample/WithEmbeded.xlsx",
|
|
3
|
+
"output": "sample/with-media.xlsx",
|
|
4
|
+
"operations": [
|
|
5
|
+
{ "op": "image.insert", "sheet": "Sheet1", "name": "绿色标记", "source": { "path": "sample/green.jpg" }, "anchor": { "kind": "oneCell", "from": { "cell": "H2" }, "width": 96, "height": 64 }, "description": "仓库自生成的纯色 JPEG" },
|
|
6
|
+
{ "op": "sheet.add", "name": "附图" },
|
|
7
|
+
{ "op": "image.insert", "sheet": "附图", "name": "蓝色标记", "source": { "path": "sample/blue.png" }, "anchor": { "kind": "oneCell", "from": { "cell": "B2" }, "width": 64, "height": 48 } }
|
|
8
|
+
]
|
|
9
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// List every picture and embedded attachment in a workbook with its size and
|
|
2
|
+
// SHA-256, and return one ready-to-run extraction request per item. A script
|
|
3
|
+
// cannot write files other than the workbook, so extraction itself is done
|
|
4
|
+
// afterwards with the image-extract and attachment-extract commands; their
|
|
5
|
+
// output.version must equal the sha256 listed here.
|
|
6
|
+
//
|
|
7
|
+
// args: { workbook, folder? }
|
|
8
|
+
// workbook path of the workbook as the extract commands should see it
|
|
9
|
+
// folder where extracted files should go (default "extracted")
|
|
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 folder = args.folder ?? 'extracted';
|
|
18
|
+
const sheets = must(await wb.inspect(), 'Inspect sheets').workbook.sheets.map(sheet => sheet.name);
|
|
19
|
+
|
|
20
|
+
// Page through a per-sheet listing; every page after the first is bound to the version of the first.
|
|
21
|
+
async function listAll(kind, sheet) {
|
|
22
|
+
const items = [];
|
|
23
|
+
for (let offset = 0; offset !== null;) {
|
|
24
|
+
const page = must(await wb.query({ [kind]: [{ sheet, offset, limit: 100 }], ...(offset ? { expectedInputVersion: wb.version } : {}) }), `List ${kind}`)[kind][0];
|
|
25
|
+
items.push(...page.items); offset = page.nextOffset;
|
|
26
|
+
}
|
|
27
|
+
return items;
|
|
28
|
+
}
|
|
29
|
+
// Stored filenames are data, never paths: keep only a short alphanumeric extension.
|
|
30
|
+
const extension = (name, fallback) => { const match = /\.([A-Za-z0-9]{1,8})$/.exec(name ?? ''); return match ? match[1].toLowerCase() : fallback; };
|
|
31
|
+
|
|
32
|
+
const images = [], attachments = [];
|
|
33
|
+
for (const [index, sheet] of sheets.entries()) {
|
|
34
|
+
for (const image of await listAll('images', sheet)) {
|
|
35
|
+
const { format, bytes, sha256, width, height } = image.metadata;
|
|
36
|
+
images.push({ sheet, name: image.name, format, width, height, bytes, sha256,
|
|
37
|
+
extract: { command: 'image-extract', request: { input: args.workbook, sheet, name: image.name, output: `${folder}/image-${index + 1}-${images.length + 1}.${extension('.' + format, 'bin')}`, expectedInputVersion: wb.version } } });
|
|
38
|
+
}
|
|
39
|
+
for (const item of await listAll('ole', sheet)) {
|
|
40
|
+
attachments.push({ sheet, id: item.id, progId: item.progId, filename: item.filename ?? null, container: item.container, bytes: item.bytes, sha256: item.sha256,
|
|
41
|
+
extract: { command: 'attachment-extract', request: { input: args.workbook, sheet, id: item.id, output: `${folder}/attachment-${index + 1}-${item.id}.${extension(item.filename, 'bin')}`, expectedInputVersion: wb.version } } });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { workbookVersion: wb.version, sheets: sheets.length, images, attachments, totalBytes: [...images, ...attachments].reduce((sum, item) => sum + item.bytes, 0) };
|