audit-e2w 0.0.0-stage → 1.11.2
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/LICENSE +21 -0
- package/README.md +147 -2
- package/cordis.patch.yml +3 -0
- package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
- package/dsh_plugins/audit-e2w/lib/index.js +114 -0
- package/dsh_plugins/audit-e2w/lib/skill.js +41 -0
- package/excel_word/README.md +380 -0
- package/excel_word/qoder_engine.py +438 -0
- package/excel_word/requirements.txt +4 -0
- package/excel_word/wesync/__init__.py +19 -0
- package/excel_word/wesync/__main__.py +6 -0
- package/excel_word/wesync/align.py +154 -0
- package/excel_word/wesync/api.py +840 -0
- package/excel_word/wesync/backup_history.py +65 -0
- package/excel_word/wesync/changelog.py +58 -0
- package/excel_word/wesync/cli.py +173 -0
- package/excel_word/wesync/commands/__init__.py +8 -0
- package/excel_word/wesync/commands/blank_cmd.py +250 -0
- package/excel_word/wesync/commands/bookmark_cmd.py +115 -0
- package/excel_word/wesync/commands/clear_cmd.py +48 -0
- package/excel_word/wesync/commands/export_cmd.py +220 -0
- package/excel_word/wesync/commands/marks_cmd.py +152 -0
- package/excel_word/wesync/commands/placeholders_cmd.py +87 -0
- package/excel_word/wesync/commands/writeback_cmd.py +513 -0
- package/excel_word/wesync/config.py +96 -0
- package/excel_word/wesync/console.py +78 -0
- package/excel_word/wesync/docx_blank.py +156 -0
- package/excel_word/wesync/docx_bookmarks.py +287 -0
- package/excel_word/wesync/docx_columns.py +257 -0
- package/excel_word/wesync/docx_edit.py +77 -0
- package/excel_word/wesync/docx_grid.py +212 -0
- package/excel_word/wesync/docx_marks.py +291 -0
- package/excel_word/wesync/docx_meta.py +157 -0
- package/excel_word/wesync/docx_newtable.py +220 -0
- package/excel_word/wesync/docx_placeholders.py +161 -0
- package/excel_word/wesync/docx_rows.py +67 -0
- package/excel_word/wesync/errors.py +5 -0
- package/excel_word/wesync/excel_blocks.py +543 -0
- package/excel_word/wesync/excel_export.py +136 -0
- package/excel_word/wesync/excel_marks.py +193 -0
- package/excel_word/wesync/excel_totals.py +53 -0
- package/excel_word/wesync/fsops.py +214 -0
- package/excel_word/wesync/gui/__init__.py +34 -0
- package/excel_word/wesync/gui/__main__.py +6 -0
- package/excel_word/wesync/gui/app.py +399 -0
- package/excel_word/wesync/gui/manual.py +68 -0
- package/excel_word/wesync/gui/pages/__init__.py +31 -0
- package/excel_word/wesync/gui/pages/_page.py +89 -0
- package/excel_word/wesync/gui/pages/batch_page.py +423 -0
- package/excel_word/wesync/gui/pages/blank_page.py +465 -0
- package/excel_word/wesync/gui/pages/bookmark_page.py +37 -0
- package/excel_word/wesync/gui/pages/export_page.py +88 -0
- package/excel_word/wesync/gui/pages/format_page.py +429 -0
- package/excel_word/wesync/gui/pages/help_page.py +92 -0
- package/excel_word/wesync/gui/pages/history_page.py +145 -0
- package/excel_word/wesync/gui/pages/marks_page.py +178 -0
- package/excel_word/wesync/gui/pages/writeback_page.py +452 -0
- package/excel_word/wesync/gui/resources.py +22 -0
- package/excel_word/wesync/gui/runner.py +74 -0
- package/excel_word/wesync/gui/store.py +34 -0
- package/excel_word/wesync/gui/theme.py +100 -0
- package/excel_word/wesync/gui/widgets/__init__.py +8 -0
- package/excel_word/wesync/gui/widgets/cards.py +20 -0
- package/excel_word/wesync/gui/widgets/filebar.py +58 -0
- package/excel_word/wesync/gui/widgets/logpane.py +110 -0
- package/excel_word/wesync/gui/widgets/nav.py +39 -0
- package/excel_word/wesync/report_format.py +1577 -0
- package/excel_word/wesync/sort_rules.py +244 -0
- package/excel_word/wesync/valuefmt.py +462 -0
- package/package.json +49 -4
- package/qoder_plugins/audit-toolbox/README.md +156 -0
- package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
"""writeback 子命令:按书签把工作簿的表块回写到 Word 表格。
|
|
2
|
+
|
|
3
|
+
匹配方式:工作簿每个表块 C 列记录的书签名 ↔ Word 里的表格(锚点段落中的书签 + 紧随其后的表格)。
|
|
4
|
+
Word 中已删除的表格(书签找不到对应表格)会被**跳过**并记日志,其余表格照常同步。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from collections import defaultdict
|
|
9
|
+
from copy import deepcopy
|
|
10
|
+
|
|
11
|
+
import docx
|
|
12
|
+
from docx.oxml.ns import qn
|
|
13
|
+
from openpyxl import load_workbook
|
|
14
|
+
from openpyxl.styles import Alignment, Font
|
|
15
|
+
|
|
16
|
+
from ..config import DELETED_BOOKMARK, EXCEL_LINK_TEXT, FILL_CODE_COLUMN, FONT_NAME, FONT_SIZE, MARK_DELETED, MARK_NO, NEW_BOOKMARK, SHEET_NAME
|
|
17
|
+
from ..console import flush_log_summary, log, log_change, warn
|
|
18
|
+
from ..align import align_blocks_to_tables
|
|
19
|
+
from ..changelog import export_changelog
|
|
20
|
+
from ..docx_bookmarks import (
|
|
21
|
+
bookmark_names,
|
|
22
|
+
cleanup_excel_markers,
|
|
23
|
+
insert_table_bookmark,
|
|
24
|
+
new_cpah_name,
|
|
25
|
+
next_bookmark_id,
|
|
26
|
+
table_index_map_by_bookmark,
|
|
27
|
+
unclaimed_table_indices,
|
|
28
|
+
)
|
|
29
|
+
from ..docx_columns import sync_columns
|
|
30
|
+
from ..docx_edit import set_cell_text
|
|
31
|
+
from ..docx_grid import body_items, build_cellmap, para_first_run_rpr, text_grid
|
|
32
|
+
from ..docx_meta import collect_table_info, dedupe_table_names
|
|
33
|
+
from ..docx_newtable import available_width_dxa, build_table, col_widths_from_excel, insert_new_table
|
|
34
|
+
from ..docx_rows import align_rows
|
|
35
|
+
from ..errors import SyncError
|
|
36
|
+
from ..excel_blocks import block_merges, parse_blocks, refresh_anchor_metadata, refresh_defined_names
|
|
37
|
+
from ..fsops import check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx, save_docx_xlsx_transaction
|
|
38
|
+
from ..sort_rules import apply_block_sort
|
|
39
|
+
from ..valuefmt import display_cell, evaluate_formula, formula_map
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _block_label(block: dict, limit: int = 30) -> str:
|
|
43
|
+
"""取表块的简短名称(去掉【表N】前缀与章节后缀并截断),用于日志。"""
|
|
44
|
+
text = (block.get("meta", {}).get("name") or "").strip()
|
|
45
|
+
if not text:
|
|
46
|
+
return ""
|
|
47
|
+
text = re.sub(r"^【(表\d+|新表)】", "", text)
|
|
48
|
+
text = re.sub(r"\s+", " ", text.split(" · 章节:")[0]).strip()
|
|
49
|
+
return text if len(text) <= limit else text[: limit - 1] + "…"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _new_table_grid(ws, block: dict, cached) -> list[list[str]]:
|
|
53
|
+
"""新表块的网格显示文本(公式取缓存或轻量求值,与回写口径一致)。"""
|
|
54
|
+
grid = []
|
|
55
|
+
col0 = block.get("col0", 2)
|
|
56
|
+
for xlsx_row in block["grid_rows"]:
|
|
57
|
+
row_texts = []
|
|
58
|
+
for c in range(block["ncols"]):
|
|
59
|
+
cell = ws.cell(xlsx_row, col0 + c)
|
|
60
|
+
raw = cell.value
|
|
61
|
+
if isinstance(raw, str) and raw.startswith("="):
|
|
62
|
+
value = cached.get((xlsx_row, col0 + c))
|
|
63
|
+
if value is None:
|
|
64
|
+
value = evaluate_formula(ws, xlsx_row, col0 + c, cached)
|
|
65
|
+
if value is None:
|
|
66
|
+
raise SyncError(
|
|
67
|
+
f"{block['code']} 新表第{len(grid) + 1}行第{c + 1}列是公式且无法计算结果"
|
|
68
|
+
f"(支持 SUM 与简单四则运算)。请先在 Excel 中打开并保存该文件后再回写"
|
|
69
|
+
)
|
|
70
|
+
raw = value
|
|
71
|
+
row_texts.append(display_cell(cell, raw))
|
|
72
|
+
grid.append(row_texts)
|
|
73
|
+
return grid
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _prev_anchor_tbl(order, code, recorded, table_index, doc, created):
|
|
77
|
+
"""新表插入点:工作簿中它之前最近的、能定位到 Word 表格的块。"""
|
|
78
|
+
for prior in reversed(order[: order.index(code)]):
|
|
79
|
+
if prior in created:
|
|
80
|
+
return created[prior], prior
|
|
81
|
+
bookmark = recorded.get(prior, "")
|
|
82
|
+
if not bookmark or bookmark in (NEW_BOOKMARK, DELETED_BOOKMARK):
|
|
83
|
+
continue
|
|
84
|
+
index = table_index.get(bookmark)
|
|
85
|
+
if index is not None:
|
|
86
|
+
return doc.tables[index]._tbl, prior
|
|
87
|
+
return None, "文档末尾"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _new_block_anchor(order, code, block, recorded, table_index, doc, created):
|
|
91
|
+
"""新表插入点:优先用表块记录的指定位置(F 列「位置:T0x之后」),否则按工作簿顺序。"""
|
|
92
|
+
after = (block.get("meta", {}).get("after") or "").strip()
|
|
93
|
+
if after and after != "末尾":
|
|
94
|
+
if after in created:
|
|
95
|
+
return created[after], after
|
|
96
|
+
bookmark = recorded.get(after, "")
|
|
97
|
+
if bookmark and bookmark not in (NEW_BOOKMARK, DELETED_BOOKMARK):
|
|
98
|
+
index = table_index.get(bookmark)
|
|
99
|
+
if index is not None:
|
|
100
|
+
return doc.tables[index]._tbl, after
|
|
101
|
+
log(f"[提醒] {code} 指定的插入位置 {after} 在 Word 中找不到对应表格,改按工作簿顺序插入")
|
|
102
|
+
return _prev_anchor_tbl(order, code, recorded, table_index, doc, created)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _create_new_tables(doc, ws, order, blocks, recorded, table_index, cached) -> int:
|
|
106
|
+
"""按「书签:新增」标记在 Word 里建表并登记书签,返回创建数。"""
|
|
107
|
+
new_codes = [code for code in order if recorded.get(code) == NEW_BOOKMARK]
|
|
108
|
+
if not new_codes:
|
|
109
|
+
return 0
|
|
110
|
+
existing_names = bookmark_names(doc.element.body)
|
|
111
|
+
bookmark_id = next_bookmark_id(doc)
|
|
112
|
+
total_dxa = available_width_dxa(doc)
|
|
113
|
+
created: dict[str, object] = {}
|
|
114
|
+
for code in new_codes:
|
|
115
|
+
block = blocks[code]
|
|
116
|
+
if not block["grid_rows"]:
|
|
117
|
+
raise SyncError(f"{code}:新表块没有网格行,请在 Excel 里填好表格内容后再同步")
|
|
118
|
+
grid = _new_table_grid(ws, block, cached)
|
|
119
|
+
merges = block_merges(ws, block)
|
|
120
|
+
widths = col_widths_from_excel(ws, block["ncols"], total_dxa, block.get("col0", 2))
|
|
121
|
+
tbl = build_table(grid, merges, block["ncols"], widths)
|
|
122
|
+
prev_tbl, prev_label = _new_block_anchor(order, code, block, recorded, table_index, doc, created)
|
|
123
|
+
name = _block_label(block, limit=60) or "新表"
|
|
124
|
+
insert_new_table(doc, prev_tbl, tbl, name)
|
|
125
|
+
bookmark = new_cpah_name(existing_names)
|
|
126
|
+
insert_table_bookmark(tbl, bookmark, bookmark_id)
|
|
127
|
+
bookmark_id += 1
|
|
128
|
+
recorded[code] = bookmark
|
|
129
|
+
created[code] = tbl
|
|
130
|
+
log(
|
|
131
|
+
f"[新增] {code} {name}:已在 {prev_label} 之后创建"
|
|
132
|
+
f"({len(grid)}行×{block['ncols']}列,合并区 {len(merges)} 处,书签 {bookmark})"
|
|
133
|
+
)
|
|
134
|
+
return len(created)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _sync_table(code: str, block: dict, tbl, ws, cached, recorder=None, name: str = "") -> dict:
|
|
138
|
+
"""同步一张表(列结构 → 行结构 → 单元格内容),返回改动统计。
|
|
139
|
+
|
|
140
|
+
recorder 不为 None 时,把逐格改动与结构改动收集为留痕记录(供导出清单/差异表)。
|
|
141
|
+
"""
|
|
142
|
+
_, cellmap_before, _ = build_cellmap(tbl)
|
|
143
|
+
old_grid = text_grid(tbl, cellmap_before)
|
|
144
|
+
|
|
145
|
+
include, inserted_cols, deleted_cols = sync_columns(tbl, ws, block, code, cached)
|
|
146
|
+
column_changed = include != list(range(block["ncols"]))
|
|
147
|
+
|
|
148
|
+
delta, deleted_rows = align_rows(tbl, len(block["grid_rows"]))
|
|
149
|
+
if delta:
|
|
150
|
+
log(f"[结构] {code}:{'新增' if delta > 0 else '删除'} {abs(delta)} 行(合计行保持在末行)")
|
|
151
|
+
if deleted_rows:
|
|
152
|
+
log(f"[结构] {code}:被删除行的首列内容 → {'、'.join(deleted_rows)}")
|
|
153
|
+
if recorder is not None:
|
|
154
|
+
if delta:
|
|
155
|
+
recorder.append({"code": code, "name": name, "kind": "增行" if delta > 0 else "删行",
|
|
156
|
+
"item": f"{'新增' if delta > 0 else '删除'} {abs(delta)} 行", "old": "", "new": ""})
|
|
157
|
+
if deleted_rows:
|
|
158
|
+
recorder.append({"code": code, "name": name, "kind": "删行明细",
|
|
159
|
+
"item": "被删行首列:" + "、".join(deleted_rows), "old": "", "new": ""})
|
|
160
|
+
if column_changed:
|
|
161
|
+
skipped_cols = block["ncols"] - len(include)
|
|
162
|
+
recorder.append({"code": code, "name": name, "kind": "列结构",
|
|
163
|
+
"item": f"新增 {inserted_cols} 列、删除 {deleted_cols} 列"
|
|
164
|
+
+ (f"、忽略整列空白 {skipped_cols} 个" if skipped_cols else ""),
|
|
165
|
+
"old": "", "new": ""})
|
|
166
|
+
|
|
167
|
+
trs, cellmap, ncols = build_cellmap(tbl)
|
|
168
|
+
if len(trs) != len(block["grid_rows"]):
|
|
169
|
+
raise SyncError(f"{code}:行数对齐失败,Word 现有 {len(trs)} 行,Excel 为 {len(block['grid_rows'])} 行")
|
|
170
|
+
if ncols != len(include):
|
|
171
|
+
raise SyncError(f"{code}:列数对齐失败,Word 现有 {ncols} 列,Excel 有效列为 {len(include)} 列")
|
|
172
|
+
|
|
173
|
+
col_rpr = {}
|
|
174
|
+
for c in range(ncols):
|
|
175
|
+
for r in range(len(trs)):
|
|
176
|
+
pos = cellmap[r][c]
|
|
177
|
+
if pos is not None and pos.owner:
|
|
178
|
+
rpr = para_first_run_rpr(pos.tc.find(qn("w:p")))
|
|
179
|
+
if rpr is not None:
|
|
180
|
+
col_rpr[c] = rpr
|
|
181
|
+
break
|
|
182
|
+
|
|
183
|
+
changed_cells = 0
|
|
184
|
+
col0 = block.get("col0", 2)
|
|
185
|
+
for r, xlsx_row in enumerate(block["grid_rows"]):
|
|
186
|
+
for word_col, excel_col in enumerate(include):
|
|
187
|
+
pos = cellmap[r][word_col]
|
|
188
|
+
cell = ws.cell(xlsx_row, col0 + excel_col)
|
|
189
|
+
if cell.hyperlink is not None:
|
|
190
|
+
warn(
|
|
191
|
+
f"{code} 第{r + 1}行第{excel_col + 1}列带有超链接元数据"
|
|
192
|
+
f"(常见于用脚本增删行导致错位),已跳过该单元格"
|
|
193
|
+
)
|
|
194
|
+
continue
|
|
195
|
+
raw = cell.value
|
|
196
|
+
if isinstance(raw, str) and raw.startswith("="):
|
|
197
|
+
cached_value = cached.get((xlsx_row, col0 + excel_col))
|
|
198
|
+
if cached_value is None:
|
|
199
|
+
cached_value = evaluate_formula(ws, xlsx_row, col0 + excel_col, cached)
|
|
200
|
+
if cached_value is None:
|
|
201
|
+
raise SyncError(
|
|
202
|
+
f"{code} 第{r + 1}行第{excel_col + 1}列是公式且无法计算结果"
|
|
203
|
+
f"(支持 SUM 与简单四则运算)。请先在 Excel 中打开并保存该文件后再回写"
|
|
204
|
+
)
|
|
205
|
+
raw = cached_value
|
|
206
|
+
text = display_cell(cell, raw)
|
|
207
|
+
if pos is None or not pos.owner:
|
|
208
|
+
if text.strip():
|
|
209
|
+
warn(
|
|
210
|
+
f"{code} 第{r + 1}行第{excel_col + 1}列在 Excel 中有值,"
|
|
211
|
+
f"但该位置在 Word 中属合并单元格,已跳过"
|
|
212
|
+
)
|
|
213
|
+
continue
|
|
214
|
+
old_value = old_grid[r][excel_col] if (r < len(old_grid) and excel_col < len(old_grid[r])) else None
|
|
215
|
+
if old_value is None and r >= len(old_grid):
|
|
216
|
+
old_value = "(新增行)"
|
|
217
|
+
if set_cell_text(pos.tc, text, col_rpr.get(word_col)):
|
|
218
|
+
changed_cells += 1
|
|
219
|
+
old_display = old_value if old_value not in (None, "") else "(空)"
|
|
220
|
+
new_display = text if text != "" else "(空)"
|
|
221
|
+
if not column_changed:
|
|
222
|
+
log_change(f"[回写] {code} 第{r + 1}行第{excel_col + 1}列:{old_display} → {new_display}")
|
|
223
|
+
if recorder is not None:
|
|
224
|
+
item = old_grid[r][0] if (r < len(old_grid) and old_grid[r]) else ""
|
|
225
|
+
recorder.append({"code": code, "name": name, "row": r + 1, "col": excel_col + 1,
|
|
226
|
+
"item": item, "old": old_display, "new": new_display, "kind": "单元格"})
|
|
227
|
+
|
|
228
|
+
if changed_cells == 0:
|
|
229
|
+
log(f"[回写] {code}:无变化")
|
|
230
|
+
elif column_changed:
|
|
231
|
+
log(f"[回写] {code}:列结构变化,共更新 {changed_cells} 个单元格(逐格明细省略)")
|
|
232
|
+
return {"cells": changed_cells, "rows": delta, "cols": inserted_cols + deleted_cols}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def cmd_writeback(args) -> int:
|
|
236
|
+
docx_path = resolve_docx(args.docx)
|
|
237
|
+
xlsx_path = resolve_xlsx(docx_path, args.excel)
|
|
238
|
+
if not xlsx_path.exists():
|
|
239
|
+
raise SyncError(f"找不到 Excel 文件:{xlsx_path}\n请先执行 export 导出,或检查 --excel 参数。")
|
|
240
|
+
if not args.dry_run:
|
|
241
|
+
check_file_free(docx_path, args.force)
|
|
242
|
+
check_file_free(xlsx_path, args.force)
|
|
243
|
+
|
|
244
|
+
doc = docx.Document(str(docx_path))
|
|
245
|
+
wb = load_workbook_for_save(xlsx_path)
|
|
246
|
+
if SHEET_NAME not in wb.sheetnames:
|
|
247
|
+
raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
|
|
248
|
+
ws = wb[SHEET_NAME]
|
|
249
|
+
cached = formula_map(xlsx_path)
|
|
250
|
+
recorder: list[dict] = []
|
|
251
|
+
|
|
252
|
+
order, blocks = parse_blocks(ws)
|
|
253
|
+
if not order:
|
|
254
|
+
raise SyncError("工作簿里没有识别到任何表块,请确认该文件由本工具导出")
|
|
255
|
+
|
|
256
|
+
recorded = {code: (blocks[code].get("bookmark") or "").strip() for code in order}
|
|
257
|
+
if not any(recorded.values()):
|
|
258
|
+
raise SyncError(
|
|
259
|
+
"该工作簿没有书记录,无法按书签匹配 Word 表格,已中止以免写错位置。\n"
|
|
260
|
+
"请先用「导出表格到 Excel」重建工作簿(或确认 --excel 指向的是本工具导出的文件)。"
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
sort_changed = 0
|
|
264
|
+
for code in order:
|
|
265
|
+
if not recorded.get(code) or recorded[code] in (NEW_BOOKMARK, DELETED_BOOKMARK):
|
|
266
|
+
continue
|
|
267
|
+
stats = apply_block_sort(ws, blocks[code], cached, dry_run=args.dry_run)
|
|
268
|
+
if stats and not args.dry_run:
|
|
269
|
+
sort_changed += 1
|
|
270
|
+
|
|
271
|
+
delete_cross = bool(getattr(args, "delete_empty_rows", False))
|
|
272
|
+
if delete_cross and all(blocks[c].get("col0", 2) == 2 for c in order):
|
|
273
|
+
log("[提示] 该工作簿为旧布局(无 B 列标记),「删除✕行」本次不生效;重新导出后即可使用。")
|
|
274
|
+
|
|
275
|
+
new_codes = [code for code in order if recorded.get(code) == NEW_BOOKMARK]
|
|
276
|
+
created_count = 0
|
|
277
|
+
if new_codes:
|
|
278
|
+
real_names = {n for n in recorded.values() if n and n not in (NEW_BOOKMARK, DELETED_BOOKMARK)}
|
|
279
|
+
pre_index = table_index_map_by_bookmark(doc, real_names, include_anchors=True)
|
|
280
|
+
if args.dry_run:
|
|
281
|
+
for code in new_codes:
|
|
282
|
+
block = blocks[code]
|
|
283
|
+
_, prev_label = _new_block_anchor(order, code, block, recorded, pre_index, doc, {})
|
|
284
|
+
log(
|
|
285
|
+
f"[新增·预演] {code} {_block_label(block)}:将在 {prev_label} 之后创建"
|
|
286
|
+
f"({len(block['grid_rows'])}行×{block['ncols']}列)"
|
|
287
|
+
)
|
|
288
|
+
else:
|
|
289
|
+
created_count = _create_new_tables(doc, ws, order, blocks, recorded, pre_index, cached)
|
|
290
|
+
for code in new_codes:
|
|
291
|
+
recorder.append({"code": code, "name": _block_label(blocks[code]), "kind": "新表",
|
|
292
|
+
"item": f"新建 {len(blocks[code]['grid_rows'])}行×{blocks[code]['ncols']}列",
|
|
293
|
+
"old": "", "new": ""})
|
|
294
|
+
|
|
295
|
+
items = body_items(doc)
|
|
296
|
+
infos = [collect_table_info(doc, items, idx, tab) for idx, tab in enumerate(doc.tables)]
|
|
297
|
+
dedupe_table_names(infos)
|
|
298
|
+
|
|
299
|
+
candidates = {name for name in recorded.values() if name and name not in (NEW_BOOKMARK, DELETED_BOOKMARK)}
|
|
300
|
+
table_index = table_index_map_by_bookmark(doc, candidates, include_anchors=True)
|
|
301
|
+
unclaimed = unclaimed_table_indices(doc, table_index)
|
|
302
|
+
|
|
303
|
+
# 书签名重复时(旧版工具曾把 C 列写脏):只有内容能对上该表的那一块可以同步,其余跳过
|
|
304
|
+
shares: dict[str, list[str]] = defaultdict(list)
|
|
305
|
+
for code in order:
|
|
306
|
+
if recorded[code] and recorded[code] not in (NEW_BOOKMARK, DELETED_BOOKMARK):
|
|
307
|
+
shares[recorded[code]].append(code)
|
|
308
|
+
align_map, _, _ = align_blocks_to_tables(doc, ws, blocks)
|
|
309
|
+
owner: dict[str, str] = {}
|
|
310
|
+
for name, codes in shares.items():
|
|
311
|
+
if len(codes) == 1:
|
|
312
|
+
owner[name] = codes[0]
|
|
313
|
+
continue
|
|
314
|
+
target = table_index.get(name)
|
|
315
|
+
matched = [code for code in codes if code in align_map and align_map[code] == target]
|
|
316
|
+
if not matched:
|
|
317
|
+
# 内容对不上(例如用户在 Excel 里改过行列表头):让候选按顺序尝试,
|
|
318
|
+
# 第一个成功同步的认领该表,失败的不认领,避免误写
|
|
319
|
+
continue
|
|
320
|
+
chosen = matched[0]
|
|
321
|
+
owner[name] = chosen
|
|
322
|
+
others = "、".join(code for code in codes if code != chosen)
|
|
323
|
+
log(f"[提示] 书签名 {name} 被 {len(codes)} 个表块共用,按内容归属 {chosen},其余跳过({others})")
|
|
324
|
+
|
|
325
|
+
marker_removed = cleanup_excel_markers(doc)
|
|
326
|
+
if marker_removed:
|
|
327
|
+
log(f"[清理] 已删除 Word 正文中遗留的 {marker_removed} 处 {EXCEL_LINK_TEXT} 文字/断链")
|
|
328
|
+
|
|
329
|
+
log(f"读取 Word:{docx_path.name}({len(doc.tables)} 张表)")
|
|
330
|
+
log(f"读取 Excel:{xlsx_path.name}(工作表:{SHEET_NAME},{len(order)} 个表块)")
|
|
331
|
+
if args.dry_run:
|
|
332
|
+
log("预演模式(--dry-run):只显示将发生的改动,不写入文件。")
|
|
333
|
+
|
|
334
|
+
total_cells = 0
|
|
335
|
+
total_rows = 0
|
|
336
|
+
total_columns = 0
|
|
337
|
+
total_cross = 0
|
|
338
|
+
mark_changed = 0
|
|
339
|
+
synced_codes: list[str] = []
|
|
340
|
+
skipped_codes: list[str] = []
|
|
341
|
+
structure_skips = 0
|
|
342
|
+
claimed_indices: dict[int, str] = {}
|
|
343
|
+
|
|
344
|
+
for code in order:
|
|
345
|
+
block = blocks[code]
|
|
346
|
+
bookmark = recorded[code]
|
|
347
|
+
label = _block_label(block)
|
|
348
|
+
if bookmark == NEW_BOOKMARK:
|
|
349
|
+
continue # 新增块的预演已在前面单独列出
|
|
350
|
+
if bookmark == DELETED_BOOKMARK:
|
|
351
|
+
skipped_codes.append(code)
|
|
352
|
+
log(f"[跳过] {code} {label}:已可逆删除(Excel 保留表块,可在「删除空白表格」页恢复)")
|
|
353
|
+
continue
|
|
354
|
+
if not bookmark:
|
|
355
|
+
skipped_codes.append(code)
|
|
356
|
+
log(f"[跳过] {code} {label}:工作簿中该表块没有书签记录,无法匹配 Word 表格")
|
|
357
|
+
continue
|
|
358
|
+
if owner.get(bookmark, code) != code:
|
|
359
|
+
skipped_codes.append(code)
|
|
360
|
+
log(f"[跳过] {code} {label}:书签名 {bookmark} 已被 {owner[bookmark]} 使用(C 列重复),已跳过")
|
|
361
|
+
continue
|
|
362
|
+
index = table_index.get(bookmark)
|
|
363
|
+
if index is None:
|
|
364
|
+
skipped_codes.append(code)
|
|
365
|
+
log(f"[跳过] {code} {label}:Word 中已找不到该表格(书签 {bookmark},可能已被删除)")
|
|
366
|
+
continue
|
|
367
|
+
if index in claimed_indices:
|
|
368
|
+
skipped_codes.append(code)
|
|
369
|
+
log(f"[跳过] {code} {label}:第 {index + 1} 张表已被 {claimed_indices[index]} 认领,跳过以免重复写入")
|
|
370
|
+
continue
|
|
371
|
+
tbl = doc.tables[index]._tbl
|
|
372
|
+
tbl_snapshot = deepcopy(tbl)
|
|
373
|
+
recorder_len = len(recorder)
|
|
374
|
+
try:
|
|
375
|
+
sync_block = block
|
|
376
|
+
cross_rows: list[int] = []
|
|
377
|
+
if delete_cross and block.get("col0", 2) == 3:
|
|
378
|
+
cross_rows = [
|
|
379
|
+
r for r in block["grid_rows"][1:]
|
|
380
|
+
if str(ws.cell(r, 2).value or "").strip() == MARK_NO
|
|
381
|
+
and not display_cell(ws.cell(r, 3)).strip().startswith("合计")
|
|
382
|
+
]
|
|
383
|
+
if cross_rows:
|
|
384
|
+
sync_block = {**block, "grid_rows": [r for r in block["grid_rows"] if r not in cross_rows]}
|
|
385
|
+
remaining_body = [
|
|
386
|
+
r for r in block["grid_rows"][1:]
|
|
387
|
+
if r not in cross_rows
|
|
388
|
+
and not display_cell(ws.cell(r, 3)).strip().startswith("合计")
|
|
389
|
+
]
|
|
390
|
+
if not remaining_body:
|
|
391
|
+
warn(
|
|
392
|
+
f"{code}:✕行覆盖全部数据行,删除后该表只剩表头/合计;"
|
|
393
|
+
f"之后改回✓恢复时因无数据行可复制格式会跳过该表,需先在 Word 手工补一行或从备份回滚。"
|
|
394
|
+
)
|
|
395
|
+
items_text = "、".join(
|
|
396
|
+
(display_cell(ws.cell(r, 3)).strip() or "(空行)")
|
|
397
|
+
for r in cross_rows
|
|
398
|
+
)
|
|
399
|
+
log(
|
|
400
|
+
f"[删除{'·预演' if args.dry_run else ''}] {code}:{len(cross_rows)} 个✕行"
|
|
401
|
+
f"{'将' if args.dry_run else '已'}从 Word 删除(Excel 保留为「已删」,改回✓可恢复):{items_text}"
|
|
402
|
+
)
|
|
403
|
+
recorder.append({"code": code, "name": label, "kind": "删行(✕)",
|
|
404
|
+
"item": f"删除 {len(cross_rows)} 个✕行:" + items_text, "old": "", "new": ""})
|
|
405
|
+
stats = _sync_table(code, sync_block, tbl, ws, cached, recorder=recorder, name=label)
|
|
406
|
+
except SyncError as exc:
|
|
407
|
+
tbl.getparent().replace(tbl, tbl_snapshot)
|
|
408
|
+
del recorder[recorder_len:]
|
|
409
|
+
skipped_codes.append(code)
|
|
410
|
+
structure_skips += 1
|
|
411
|
+
log(f"[跳过] {code} {label}:结构不符,该表已回滚、未留下部分修改({exc})")
|
|
412
|
+
continue
|
|
413
|
+
if cross_rows and not args.dry_run:
|
|
414
|
+
for r in cross_rows:
|
|
415
|
+
cell = ws.cell(r, 2)
|
|
416
|
+
cell.value = MARK_DELETED
|
|
417
|
+
cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color="808080")
|
|
418
|
+
cell.fill = FILL_CODE_COLUMN
|
|
419
|
+
cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
420
|
+
mark_changed += len(cross_rows)
|
|
421
|
+
total_cross += len(cross_rows)
|
|
422
|
+
synced_codes.append(code)
|
|
423
|
+
claimed_indices[index] = code
|
|
424
|
+
total_cells += stats["cells"]
|
|
425
|
+
total_rows += abs(stats["rows"])
|
|
426
|
+
total_columns += stats["cols"]
|
|
427
|
+
|
|
428
|
+
if getattr(args, "recorder", None) is not None:
|
|
429
|
+
args.recorder.extend(recorder)
|
|
430
|
+
|
|
431
|
+
if unclaimed:
|
|
432
|
+
log(f"[提示] Word 中有 {len(unclaimed)} 张表格未在工作簿中找到对应记录,已保持原样")
|
|
433
|
+
|
|
434
|
+
if not synced_codes and not created_count and not new_codes:
|
|
435
|
+
flush_log_summary()
|
|
436
|
+
log(f"没有任何表块匹配到 Word 表格,未做任何写入(共 {len(order)} 个表块,全部跳过)。")
|
|
437
|
+
return 0
|
|
438
|
+
|
|
439
|
+
meta_changed = 0
|
|
440
|
+
for code in synced_codes:
|
|
441
|
+
block = blocks[code]
|
|
442
|
+
index = table_index.get(recorded[code])
|
|
443
|
+
if index is None or index >= len(infos):
|
|
444
|
+
continue
|
|
445
|
+
# 元数据里的书签名必须沿用工作簿里记录的那个(配对依据),不能被占位名覆盖
|
|
446
|
+
info = {**infos[index], "bookmark": recorded[code]}
|
|
447
|
+
row = block["anchor_row"]
|
|
448
|
+
before = [ws.cell(row, col).value for col in range(1, 6)]
|
|
449
|
+
refresh_anchor_metadata(
|
|
450
|
+
ws,
|
|
451
|
+
block,
|
|
452
|
+
info,
|
|
453
|
+
docx_path.name,
|
|
454
|
+
with_link=block.get("meta", {}).get("link_col") is not None or code in new_codes,
|
|
455
|
+
ncols=block["ncols"],
|
|
456
|
+
)
|
|
457
|
+
after = [ws.cell(row, col).value for col in range(1, 6)]
|
|
458
|
+
if before != after:
|
|
459
|
+
meta_changed += 1
|
|
460
|
+
|
|
461
|
+
name_changes = refresh_defined_names(wb, {code: blocks[code] for code in synced_codes})
|
|
462
|
+
for item in name_changes:
|
|
463
|
+
log(f"[定位] 定义名称已更新:{item}")
|
|
464
|
+
|
|
465
|
+
flush_log_summary()
|
|
466
|
+
reasons = []
|
|
467
|
+
if structure_skips:
|
|
468
|
+
reasons.append(f"结构不符 {structure_skips} 张")
|
|
469
|
+
other_skips = len(skipped_codes) - structure_skips
|
|
470
|
+
if other_skips:
|
|
471
|
+
reasons.append(f"已删除/缺少书签 {other_skips} 张")
|
|
472
|
+
skip_note = f",跳过 {len(skipped_codes)} 张表({'、'.join(reasons)})" if skipped_codes else ""
|
|
473
|
+
new_note = f",新增 {created_count} 张表" if created_count else ""
|
|
474
|
+
sort_note = f",排序 {sort_changed} 张表" if sort_changed else ""
|
|
475
|
+
cross_note = f",删除✕行 {total_cross} 行" if total_cross else ""
|
|
476
|
+
log(
|
|
477
|
+
f"合计:同步 {len(synced_codes)} 张表(改动 {total_cells} 个单元格,"
|
|
478
|
+
f"{total_rows} 行结构,{total_columns} 列结构){new_note}{sort_note}{cross_note}{skip_note}。"
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
if args.dry_run:
|
|
482
|
+
log("预演结束,未写入任何文件。")
|
|
483
|
+
return 0
|
|
484
|
+
|
|
485
|
+
docx_changed = bool(total_cells or total_rows or total_columns or marker_removed or created_count)
|
|
486
|
+
xlsx_changed = bool(meta_changed or name_changes or sort_changed or mark_changed)
|
|
487
|
+
if not docx_changed and not xlsx_changed:
|
|
488
|
+
log("Word 与 Excel 数据一致,未做任何写入。")
|
|
489
|
+
return 0
|
|
490
|
+
|
|
491
|
+
backups = save_docx_xlsx_transaction(
|
|
492
|
+
docx_path=docx_path if docx_changed else None,
|
|
493
|
+
doc=doc if docx_changed else None,
|
|
494
|
+
xlsx_path=xlsx_path if xlsx_changed else None,
|
|
495
|
+
wb=wb if xlsx_changed else None,
|
|
496
|
+
backup=getattr(args, "backup", True),
|
|
497
|
+
)
|
|
498
|
+
xlsx_backup = backups.get(xlsx_path) if xlsx_changed else None
|
|
499
|
+
docx_backup = backups.get(docx_path) if docx_changed else None
|
|
500
|
+
|
|
501
|
+
if xlsx_changed:
|
|
502
|
+
log(
|
|
503
|
+
f"[定位] 已保存 {xlsx_path.name}(元数据 {meta_changed} 处、定义名称 {len(name_changes)} 处"
|
|
504
|
+
+ (f"、✕行标记已删 {mark_changed} 行" if mark_changed else "")
|
|
505
|
+
+ f")"
|
|
506
|
+
+ (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else "")
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
if docx_changed:
|
|
510
|
+
log(f"[回写] 已保存 {docx_path.name}" + (f"(原文件已备份:{docx_backup.name})" if docx_backup else ""))
|
|
511
|
+
if getattr(args, "changelog", False):
|
|
512
|
+
export_changelog(recorder, xlsx_path, docx_path.name)
|
|
513
|
+
return 0
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""全局常量与正则:工作表名、书签前缀、字体与配色、边框/对齐映射、各种上限。"""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from openpyxl.styles import PatternFill
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
SHEET_NAME = "表格汇总"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
CODE_RE = re.compile(r"^T\d{2,}$")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
DATE_RE = re.compile(r"^\d{4}\s*年\s*\d{1,2}\s*月\s*\d{1,2}\s*日$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
NUMBER_RE = re.compile(r"^-?\d[\d,]*(\.\d+)?$")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
EXCEL_LINK_TEXT = "〔→Excel〕"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
BOOKMARK_PREFIX = "Table_"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# 新表标记:表块 C 列写「书签:新增」表示要在 Word 里新建这张表
|
|
27
|
+
NEW_BOOKMARK = "新增"
|
|
28
|
+
|
|
29
|
+
# 可逆删除标记:表块 C 列写「书签:已删除」表示 Word 里的表已删、表块保留待恢复
|
|
30
|
+
DELETED_BOOKMARK = "已删除"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
LEGACY_BOOKMARK_RE = re.compile(r"^TBL_\d+$")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
META_SCAN_COLUMNS = 16
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# B 列行标记:表头行写「表头」;数据行除首列外任一列有内容=✓、全空=✕;
|
|
40
|
+
# 勾选「删除✕行」同步后,被删行在 Excel 保留为「已删」(改回✓可恢复)
|
|
41
|
+
MARK_HEADER = "表头"
|
|
42
|
+
MARK_YES = "✓"
|
|
43
|
+
MARK_NO = "✕"
|
|
44
|
+
MARK_DELETED = "已删"
|
|
45
|
+
MARK_VALUES = (MARK_HEADER, MARK_YES, MARK_NO, MARK_DELETED)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
MAX_COLUMN_SHIFT = 4
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
SKIP_COLUMN = -1
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
MAX_LOG_LINES = 200
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
FONT_NAME = "宋体"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
FONT_SIZE = 9
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
FILL_CODE_COLUMN = PatternFill("solid", fgColor="F2F2F2")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
FILL_ANCHOR = PatternFill("solid", fgColor="FFF2CC")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
BORDER_MAP = {
|
|
70
|
+
"single": "thin",
|
|
71
|
+
"double": "double",
|
|
72
|
+
"dotted": "dotted",
|
|
73
|
+
"dashed": "dashed",
|
|
74
|
+
"dashDot": "dashDot",
|
|
75
|
+
"dashDotDot": "dashDotDot",
|
|
76
|
+
"thick": "medium",
|
|
77
|
+
"wave": "thin",
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
JC_MAP = {"center": "center", "right": "right", "both": "justify", "distribute": "justify", "left": "left"}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
VA_MAP = {"center": "center", "bottom": "bottom", "top": "top"}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
CELL_REF_RE = re.compile(r"^\$?([A-Za-z]{1,3})\$?(\d+)$")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
RANGE_REF_RE = re.compile(r"^\$?([A-Za-z]{1,3})\$?(\d+)\s*:\s*\$?([A-Za-z]{1,3})\$?(\d+)$")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
SUM_RE = re.compile(r"^SUM\s*\((.*)\)$", re.IGNORECASE)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
ARITH_OK_RE = re.compile(r"^[0-9+\-*/(). ]+$")
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""中文日志输出:普通日志、逐格改动日志(超限折叠)、警告与用法提示。
|
|
2
|
+
|
|
3
|
+
默认把日志打印到控制台;设置日志接收器后(界面用)改为投递给接收器,
|
|
4
|
+
因此命令行行为不受影响。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Callable
|
|
8
|
+
|
|
9
|
+
from .config import MAX_LOG_LINES
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
_log_state = {"shown": 0, "suppressed": 0}
|
|
13
|
+
_log_sink: Callable[[str], None] | None = None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def set_log_sink(sink: Callable[[str], None] | None) -> None:
|
|
17
|
+
"""设置日志接收器;传 None 恢复为打印到控制台。"""
|
|
18
|
+
global _log_sink
|
|
19
|
+
_log_sink = sink
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def reset_log_state() -> None:
|
|
23
|
+
"""重置逐格日志的折叠计数(每个任务开始前调用)。"""
|
|
24
|
+
_log_state["shown"] = 0
|
|
25
|
+
_log_state["suppressed"] = 0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _emit(message: str) -> None:
|
|
29
|
+
if _log_sink is not None:
|
|
30
|
+
_log_sink(message)
|
|
31
|
+
else:
|
|
32
|
+
print(message, flush=True)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def log(message: str = "") -> None:
|
|
36
|
+
_emit(message)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def log_change(message: str) -> None:
|
|
40
|
+
"""逐格改动日志,超过上限后折叠,避免刷屏。"""
|
|
41
|
+
if _log_state["shown"] < MAX_LOG_LINES:
|
|
42
|
+
_emit(message)
|
|
43
|
+
_log_state["shown"] += 1
|
|
44
|
+
else:
|
|
45
|
+
_log_state["suppressed"] += 1
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def flush_log_summary() -> None:
|
|
49
|
+
if _log_state["suppressed"]:
|
|
50
|
+
log(f"...(另有 {_log_state['suppressed']} 条改动日志已省略)")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def warn(message: str) -> None:
|
|
54
|
+
_emit(f"警告:{message}")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
USAGE_HINT = """用法:word_excel_sync.py <子命令> "<Word文件.docx>" [选项]
|
|
58
|
+
|
|
59
|
+
子命令:
|
|
60
|
+
export 把 Word 全部表格导出为 Excel(含书签、跳转链接),会重建工作簿
|
|
61
|
+
rejudge 按工作簿当前内容重新判定 B 列表头/✓/✕(只改标记,不改数据)
|
|
62
|
+
bookmark 只重建/迁移 Word 书签并清理正文遗留的〔→Excel〕文字,不动 Excel 数据
|
|
63
|
+
writeback 把 Excel 的改动(含增行删行、增列删列)回写到 Word;
|
|
64
|
+
--with-marks / --with-placeholders 可叠加同步标注与占位符
|
|
65
|
+
marks 把 Word 高亮标记导出/刷新到工作簿「链接标注」表
|
|
66
|
+
marks-sync 把「链接标注」表填写的内容同步回 Word
|
|
67
|
+
placeholders 按 Word 的 {字段名} 补齐工作簿「正文信息」填写骨架
|
|
68
|
+
placeholders-sync 把「正文信息」表填好的值写回 Word 占位符
|
|
69
|
+
blank 删除空白表格(整表全空/仅表头有字),--pick 编号 或 --all 选择后才删
|
|
70
|
+
clear-bookmarks 删除本工具写入的书签,保留 Word 自带书签
|
|
71
|
+
|
|
72
|
+
常用示例:
|
|
73
|
+
.venv\\Scripts\\python.exe word_excel_sync.py bookmark "0.0.0审计报告.docx"
|
|
74
|
+
.venv\\Scripts\\python.exe word_excel_sync.py writeback "0.0.0审计报告.docx" --dry-run
|
|
75
|
+
.venv\\Scripts\\python.exe word_excel_sync.py export "0.0.0审计报告.docx"
|
|
76
|
+
|
|
77
|
+
各子命令的完整参数请执行:word_excel_sync.py <子命令> -h
|
|
78
|
+
"""
|