audit-e2w 1.11.2 → 1.11.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +152 -148
  2. package/dsh_plugins/audit-e2w/lib/index.js +9 -1
  3. package/dsh_plugins/audit-e2w/lib/skill.js +3 -2
  4. package/excel_word/README.md +45 -37
  5. package/excel_word/qoder_engine.py +10 -11
  6. package/excel_word/wesync/__init__.py +1 -1
  7. package/excel_word/wesync/ai/__init__.py +52 -0
  8. package/excel_word/wesync/ai/actions.py +369 -0
  9. package/excel_word/wesync/ai/client.py +340 -0
  10. package/excel_word/wesync/ai/config.py +291 -0
  11. package/excel_word/wesync/ai/docs.py +177 -0
  12. package/excel_word/wesync/ai/prompts.py +288 -0
  13. package/excel_word/wesync/ai/tasks/__init__.py +26 -0
  14. package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
  15. package/excel_word/wesync/ai/tasks/combined.py +123 -0
  16. package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
  17. package/excel_word/wesync/ai/tasks/headings.py +119 -0
  18. package/excel_word/wesync/ai/tasks/help_task.py +69 -0
  19. package/excel_word/wesync/ai/tasks/roles.py +128 -0
  20. package/excel_word/wesync/align.py +1 -0
  21. package/excel_word/wesync/api.py +544 -92
  22. package/excel_word/wesync/backup_history.py +44 -9
  23. package/excel_word/wesync/cli.py +19 -1
  24. package/excel_word/wesync/commands/blank_cmd.py +59 -30
  25. package/excel_word/wesync/commands/bookmark_cmd.py +41 -10
  26. package/excel_word/wesync/commands/clear_cmd.py +5 -3
  27. package/excel_word/wesync/commands/export_cmd.py +270 -220
  28. package/excel_word/wesync/commands/incremental_cmd.py +157 -0
  29. package/excel_word/wesync/commands/marks_cmd.py +24 -16
  30. package/excel_word/wesync/commands/placeholders_cmd.py +12 -7
  31. package/excel_word/wesync/commands/writeback_cmd.py +72 -116
  32. package/excel_word/wesync/config.py +3 -2
  33. package/excel_word/wesync/console.py +9 -2
  34. package/excel_word/wesync/docx_bookmarks.py +12 -5
  35. package/excel_word/wesync/docx_columns.py +1 -1
  36. package/excel_word/wesync/docx_marks.py +183 -75
  37. package/excel_word/wesync/docx_placeholders.py +65 -26
  38. package/excel_word/wesync/excel_blocks.py +144 -185
  39. package/excel_word/wesync/excel_export.py +15 -8
  40. package/excel_word/wesync/excel_marks.py +265 -193
  41. package/excel_word/wesync/fsops.py +11 -6
  42. package/excel_word/wesync/gui/__init__.py +21 -2
  43. package/excel_word/wesync/gui/app.py +243 -29
  44. package/excel_word/wesync/gui/manual.py +5 -3
  45. package/excel_word/wesync/gui/pages/__init__.py +53 -4
  46. package/excel_word/wesync/gui/pages/_page.py +129 -7
  47. package/excel_word/wesync/gui/pages/ai_page.py +854 -0
  48. package/excel_word/wesync/gui/pages/batch_page.py +64 -31
  49. package/excel_word/wesync/gui/pages/blank_page.py +529 -464
  50. package/excel_word/wesync/gui/pages/bookmark_page.py +97 -37
  51. package/excel_word/wesync/gui/pages/export_page.py +140 -87
  52. package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
  53. package/excel_word/wesync/gui/pages/format_page.py +551 -429
  54. package/excel_word/wesync/gui/pages/help_page.py +73 -7
  55. package/excel_word/wesync/gui/pages/history_page.py +167 -144
  56. package/excel_word/wesync/gui/pages/marks_page.py +210 -177
  57. package/excel_word/wesync/gui/pages/settings_page.py +450 -0
  58. package/excel_word/wesync/gui/pages/writeback_page.py +167 -146
  59. package/excel_word/wesync/gui/runner.py +29 -13
  60. package/excel_word/wesync/gui/store.py +23 -7
  61. package/excel_word/wesync/gui/theme.py +220 -49
  62. package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
  63. package/excel_word/wesync/gui/widgets/cards.py +124 -5
  64. package/excel_word/wesync/gui/widgets/chips.py +565 -0
  65. package/excel_word/wesync/gui/widgets/filebar.py +1 -1
  66. package/excel_word/wesync/gui/widgets/logpane.py +24 -8
  67. package/excel_word/wesync/gui/widgets/nav.py +267 -12
  68. package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
  69. package/excel_word/wesync/report_format.py +9 -1
  70. package/excel_word/wesync/settings.py +35 -0
  71. package/excel_word/wesync/sort_rules.py +75 -26
  72. package/excel_word/wesync/valuefmt.py +40 -17
  73. package/package.json +53 -51
  74. package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
  75. package/qoder_plugins/audit-toolbox/README.md +159 -156
  76. package/qoder_plugins/audit-toolbox/catalog.mjs +13 -13
@@ -1,220 +1,270 @@
1
- """export 子命令:按当前 Word 重新生成工作簿,并把书签整表锚定。
2
-
3
- 导出时会先按内容把现有工作簿的表块与当前 Word 表格对齐,沿用原有的书签名
4
- (对不上的块/表会自动报告),然后把书签重建到表格内部(覆盖整张表)。
5
- """
6
-
7
- import docx
8
- from openpyxl import load_workbook
9
-
10
- from ..align import apply_table_bookmarks, plan_table_bookmarks, split_bookmark_updates
11
- from ..config import DELETED_BOOKMARK, EXCEL_LINK_TEXT, NEW_BOOKMARK, SHEET_NAME
12
- from ..console import log
13
- from ..docx_bookmarks import cleanup_excel_markers
14
- from ..docx_grid import body_items
15
- from ..docx_marks import ensure_mark_bookmarks, find_marks, processed_marks
16
- from ..docx_meta import collect_table_info, dedupe_table_names
17
- from ..docx_placeholders import VALUES_SHEET, init_placeholder_sheet, read_placeholder_values, scan_placeholders
18
- from ..errors import SyncError
19
- from ..excel_blocks import carry_over_deleted_blocks, parse_blocks, read_recorded_bookmarks, rejudge_marks
20
- from ..excel_export import export_workbook
21
- from ..excel_marks import SHEET_MARKS, build_marks_sheet, read_previous_marks
22
- from ..fsops import backup_file, check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx
23
-
24
-
25
- def _code_number(code: str) -> int:
26
- try:
27
- return int(code[1:])
28
- except ValueError:
29
- return 0
30
-
31
-
32
- def _removed_block_hints(xlsx_path, recorded: dict[str, str], blocks_old: dict, plan: dict) -> list[str]:
33
- """导出前提醒:现有工作簿里有块在 Word 中已找不到对应表格(按实际对齐结果判断)。"""
34
- if not recorded:
35
- if xlsx_path.exists():
36
- return ["[提醒] 现有工作簿没有书签记录,本次导出将按当前 Word 重建并重新登记书签。"]
37
- return []
38
- missing = sorted(
39
- (
40
- code for code in plan["unmatched_codes"]
41
- if (blocks_old.get(code) or {}).get("bookmark") != DELETED_BOOKMARK
42
- ),
43
- key=_code_number,
44
- )
45
- unnamed = sorted((code for code, name in recorded.items() if not name), key=_code_number)
46
- hints: list[str] = []
47
- if missing:
48
- shown = "、".join(missing[:8]) + ("…" if len(missing) > 8 else "")
49
- hints.append(
50
- f"[提醒] 现有工作簿中有 {len(missing)} 个表块在 Word 中已找不到对应表格"
51
- f"(可能是已删除的表:{shown});导出将按当前 Word 重建,这些块会消失。"
52
- )
53
- if unnamed:
54
- hints.append(f"[提醒] 现有工作簿中有 {len(unnamed)} 个表块没有书签记录,导出后将重新登记书签。")
55
- return hints
56
-
57
-
58
- def _load_previous_workbook(xlsx_path):
59
- """读取现有工作簿(表块 + 工作表),用于沿用书签名;不存在或读不了时返回 (None, {})。"""
60
- if not xlsx_path.exists():
61
- return None, {}
62
- try:
63
- workbook = load_workbook(str(xlsx_path))
64
- except Exception as exc: # 文件被占用或损坏时不阻断导出
65
- log(f"[提醒] 读取现有工作簿失败({exc}),本次不沿用旧书签名。")
66
- return None, {}
67
- if SHEET_NAME not in workbook.sheetnames:
68
- return None, {}
69
- ws = workbook[SHEET_NAME]
70
- _, blocks = parse_blocks(ws)
71
- return ws, blocks
72
-
73
-
74
- def cmd_export(args) -> int:
75
- docx_path = resolve_docx(args.docx)
76
- xlsx_path = resolve_xlsx(docx_path, args.excel)
77
- if not args.dry_run:
78
- check_file_free(docx_path, args.force)
79
- check_file_free(xlsx_path, args.force)
80
-
81
- doc = docx.Document(str(docx_path))
82
- items = body_items(doc)
83
- infos = [collect_table_info(doc, items, idx, tab) for idx, tab in enumerate(doc.tables)]
84
- dedupe_table_names(infos)
85
- recorded = {
86
- code: name
87
- for code, name in read_recorded_bookmarks(xlsx_path).items()
88
- if name not in (NEW_BOOKMARK, DELETED_BOOKMARK)
89
- }
90
- ws_old, blocks_old = _load_previous_workbook(xlsx_path)
91
- previous_marks = read_previous_marks(xlsx_path)
92
- marks = find_marks(doc)
93
- processed = processed_marks(doc, {mark.bookmark for mark in marks if mark.bookmark})
94
- ph_fields = scan_placeholders(doc)
95
- ph_values_old = {}
96
- if ph_fields and xlsx_path.exists():
97
- try:
98
- ph_values_old = read_placeholder_values(xlsx_path, resolve_formulas=False)
99
- except Exception as exc: # 旧工作簿读不了时不影响导出,只是带不过来已填值
100
- log(f"[提醒] 读取原「{VALUES_SHEET}」表失败({exc}),本次无法保留已填值。")
101
-
102
- plan = plan_table_bookmarks(doc, ws_old, blocks_old, recorded, name_unmatched=True)
103
- name_by_index = {index: name for index, name in plan["assignments"]}
104
- for info in infos:
105
- info["bookmark"] = name_by_index.get(info["index"], "")
106
-
107
- log(f"读取 Word:{docx_path.name}")
108
- log(f"发现表格:{len(infos)} 张" + ("(无表格,工作表「" + SHEET_NAME + "」将为空)" if not infos else ""))
109
- with_links = not getattr(args, "no_excel_links", False)
110
- for info in infos:
111
- log(
112
- f" {info['code']} {info['name']}({info['nrows']} 行 × {info['ncols']} 列,"
113
- f"合并区 {sum(1 for m in info['merges'] if m[2] > 1 or m[3] > 1)} 处,书签 {info['bookmark']})"
114
- )
115
- log(f"目标工作簿:{xlsx_path.name}(工作表:{SHEET_NAME})")
116
- log(f"高亮标记:{len(marks)} 处(将写入工作表「{SHEET_MARKS}」)")
117
- if ph_fields:
118
- log(f"正文占位符:{len(ph_fields)} 个(将写入工作表「{VALUES_SHEET}」)")
119
- else:
120
- log(f"正文占位符:未发现(工作表「{VALUES_SHEET}」将为空)")
121
- for hint in _removed_block_hints(xlsx_path, recorded, blocks_old, plan):
122
- log(hint)
123
-
124
- if args.dry_run:
125
- log("预演模式(--dry-run):以上为将导出的内容,未写入任何文件。")
126
- return 0
127
-
128
- assignments, remove_names = split_bookmark_updates(doc, plan["assignments"], recorded)
129
- result = apply_table_bookmarks(doc, assignments, remove_names)
130
- if result["inserted"]:
131
- log(f"[书签] 已把 {result['inserted']} 个书签整表锚定(点击可选中整张表格)")
132
- created_marks = ensure_mark_bookmarks(doc, marks)
133
- if created_marks:
134
- log(f"[标记] 已为 {created_marks} 处高亮标记插入定位书签(MRK_xxxx,正文外观不变)")
135
- removed_markers = cleanup_excel_markers(doc)
136
- if removed_markers:
137
- log(f"[清理] 已删除 Word 正文中遗留的 {removed_markers} 处 {EXCEL_LINK_TEXT} 文字/断链")
138
-
139
- workbook = export_workbook(
140
- infos, docx_path.name, with_links=with_links,
141
- totals_formula=not getattr(args, "no_total_formulas", False),
142
- )
143
- if ws_old is not None:
144
- carried = carry_over_deleted_blocks(workbook, ws_old, blocks_old)
145
- if carried:
146
- log(f"[保留] 已可逆删除的 {len(carried)} 个表块原样保留({'、'.join(carried)}),可在「删除空白表格」页恢复。")
147
- from ..sort_rules import carry_over_sort_settings
148
-
149
- sort_carried = carry_over_sort_settings(workbook, ws_old, blocks_old)
150
- if sort_carried:
151
- log(f"[保留] {len(sort_carried)} 个表块的排序设置已按书签沿用({'、'.join(sort_carried)})。")
152
- mark_stats = build_marks_sheet(workbook, docx_path.name, marks, previous_marks, processed)
153
- log(
154
- f"[标记] 工作表「{SHEET_MARKS}」已写入 {mark_stats['marks']} 行"
155
- + (f",{mark_stats['processed']} 行已处理" if mark_stats.get("processed") else "")
156
- + (f",另有 {mark_stats['orphans']} 行已删除记录" if mark_stats["orphans"] else "")
157
- )
158
- if ph_fields:
159
- ws_ph = init_placeholder_sheet(workbook)
160
- for field in ph_fields:
161
- ws_ph.append([field, ph_values_old.get(field, "")])
162
- kept = sum(1 for f in ph_fields if ph_values_old.get(f))
163
- log(
164
- f"[占位符] 工作表「{VALUES_SHEET}」已写入 {len(ph_fields)} 个字段"
165
- + (f",保留已填值 {kept} 个" if kept else "(待填写)")
166
- )
167
- else:
168
- init_placeholder_sheet(workbook)
169
- log(f"[占位符] 正文无 {{字段名}},工作表「{VALUES_SHEET}」已创建为空表。")
170
- backup = getattr(args, "backup", True)
171
- if not backup:
172
- log("[导出] 按选项不备份原文件(--no-backup / 界面取消勾选),直接覆盖。")
173
- xlsx_backup = backup_file(xlsx_path) if backup else None
174
- workbook.save(str(xlsx_path))
175
- log(f"[导出] 已写入 {xlsx_path.name}" + (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else ""))
176
-
177
- if result["removed"] or result["inserted"] or created_marks or removed_markers:
178
- docx_backup = backup_file(docx_path) if backup else None
179
- doc.save(str(docx_path))
180
- log(f"[导出] 已更新 {docx_path.name}" + (f"(原文件已备份:{docx_backup.name})" if docx_backup else ""))
181
- else:
182
- log("[导出] Word 中的书签已是目标状态,无需改动。")
183
- return 0
184
-
185
-
186
- def cmd_rejudge(args) -> int:
187
- """按工作簿当前内容重新判定 B 列表头/✓/✕(只改标记,不改数据、不改 Word)。"""
188
- docx_path = resolve_docx(args.docx)
189
- xlsx_path = resolve_xlsx(docx_path, args.excel)
190
- if not xlsx_path.exists():
191
- raise SyncError(f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」。")
192
- if not args.dry_run:
193
- check_file_free(xlsx_path, args.force)
194
- workbook = load_workbook_for_save(xlsx_path)
195
- if SHEET_NAME not in workbook.sheetnames:
196
- raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
197
- ws = workbook[SHEET_NAME]
198
- _, blocks = parse_blocks(ws)
199
- if not blocks:
200
- raise SyncError("工作簿中没有表块,请先执行「导出表格到 Excel」")
201
- log(f"读取工作簿:{xlsx_path.name}(表块 {len(blocks)} 个)")
202
- stats = rejudge_marks(ws, blocks)
203
- if stats["old"]:
204
- log(
205
- f"[提醒] {'、'.join(stats['old'])} 为旧布局(没有标记列),无法重新判定;"
206
- f"请执行一次「导出表格到 Excel」升级为新布局。"
207
- )
208
- prefix = "[判定·预演]" if args.dry_run else "[判定]"
209
- log(f"{prefix} 重新判定 {stats['rows']} 行,标记变化 {stats['changed']} 行(表头/✓/✕;「已删」行保持原样)")
210
- if args.dry_run:
211
- log("预演模式(--dry-run):未写入任何文件。")
212
- return 0
213
- if not stats["changed"]:
214
- log("标记与当前内容一致,工作簿无需写入。")
215
- return 0
216
- backup = getattr(args, "backup", True)
217
- xlsx_backup = backup_file(xlsx_path) if backup else None
218
- workbook.save(str(xlsx_path))
219
- log(f"[判定] 已保存 {xlsx_path.name}" + (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else ""))
220
- return 0
1
+ """export 子命令:按当前 Word 重新生成工作簿,并把书签整表锚定。
2
+
3
+ 导出时会先按内容把现有工作簿的表块与当前 Word 表格对齐,沿用原有的书签名
4
+ (对不上的块/表会自动报告),然后把书签重建到表格内部(覆盖整张表)。
5
+ """
6
+
7
+ import docx
8
+ from openpyxl import Workbook, load_workbook
9
+
10
+ from ..align import apply_table_bookmarks, plan_table_bookmarks, split_bookmark_updates
11
+ from ..config import DELETED_BOOKMARK, EXCEL_LINK_TEXT, NEW_BOOKMARK, SHEET_NAME, SHEET_NEW_TABLES
12
+ from ..console import log
13
+ from ..docx_bookmarks import cleanup_excel_markers
14
+ from ..docx_grid import body_items
15
+ from ..docx_marks import ensure_mark_bookmarks, find_marks, processed_marks
16
+ from ..docx_meta import collect_table_info, dedupe_table_names
17
+ from ..docx_placeholders import VALUES_SHEET, init_placeholder_sheet, read_placeholder_values, scan_placeholders
18
+ from ..errors import SyncError
19
+ from ..excel_blocks import carry_over_deleted_blocks, parse_blocks, read_recorded_bookmarks, rejudge_marks
20
+ from ..excel_export import export_workbook
21
+ from ..excel_marks import SHEET_MARKS, build_marks_sheet, read_previous_marks
22
+ from ..fsops import check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx, save_docx_xlsx_transaction
23
+
24
+
25
+ def _code_number(code: str) -> int:
26
+ try:
27
+ return int(code[1:])
28
+ except ValueError:
29
+ return 0
30
+
31
+
32
+ def _removed_block_hints(xlsx_path, recorded: dict[str, str], blocks_old: dict, plan: dict) -> list[str]:
33
+ """导出前提醒:现有工作簿里有块在 Word 中已找不到对应表格(按实际对齐结果判断)。"""
34
+ if not recorded:
35
+ if xlsx_path.exists():
36
+ return ["[提醒] 现有工作簿没有书签记录,本次导出将按当前 Word 重建并重新登记书签。"]
37
+ return []
38
+ missing = sorted(
39
+ (
40
+ code for code in plan["unmatched_codes"]
41
+ if (blocks_old.get(code) or {}).get("bookmark") != DELETED_BOOKMARK
42
+ ),
43
+ key=_code_number,
44
+ )
45
+ unnamed = sorted((code for code, name in recorded.items() if not name), key=_code_number)
46
+ hints: list[str] = []
47
+ if missing:
48
+ shown = "、".join(missing[:8]) + ("…" if len(missing) > 8 else "")
49
+ hints.append(
50
+ f"[提醒] 现有工作簿中有 {len(missing)} 个表块在 Word 中已找不到对应表格"
51
+ f"(可能是已删除的表:{shown});导出将按当前 Word 重建,这些块会消失。"
52
+ )
53
+ if unnamed:
54
+ hints.append(f"[提醒] 现有工作簿中有 {len(unnamed)} 个表块没有书签记录,导出后将重新登记书签。")
55
+ return hints
56
+
57
+
58
+ def _load_previous_workbook(xlsx_path):
59
+ """读取现有工作簿(表块 + 工作表),用于沿用书签名;不存在或读不了时返回 (None, {})。"""
60
+ if not xlsx_path.exists():
61
+ return None, {}
62
+ try:
63
+ workbook = load_workbook(str(xlsx_path))
64
+ except Exception as exc: # 文件被占用或损坏时不阻断导出
65
+ log(f"[提醒] 读取现有工作簿失败({exc}),本次不沿用旧书签名。")
66
+ return None, {}
67
+ if SHEET_NAME not in workbook.sheetnames:
68
+ return None, {}
69
+ blocks: dict[str, dict] = {}
70
+ for sheet_name in (SHEET_NAME, SHEET_NEW_TABLES):
71
+ if sheet_name not in workbook.sheetnames:
72
+ continue
73
+ ws = workbook[sheet_name]
74
+ _, sheet_blocks = parse_blocks(ws)
75
+ duplicate = set(sheet_blocks) & set(blocks)
76
+ if duplicate:
77
+ raise SyncError(f"工作簿中表编号重复:{'、'.join(sorted(duplicate))}。请修正后再导出。")
78
+ for code, block in sheet_blocks.items():
79
+ block["_ws"] = ws
80
+ blocks[code] = block
81
+ return workbook[SHEET_NAME], blocks
82
+
83
+
84
+ def _empty_export_workbook(xlsx_path):
85
+ """全量导出仍清空重建;仅原 XLSM 额外载入并保留 VBA 包。"""
86
+ if not xlsx_path.exists() or xlsx_path.suffix.lower() != ".xlsm":
87
+ return Workbook()
88
+ try:
89
+ workbook = load_workbook_for_save(xlsx_path, keep_links=False)
90
+ except Exception as exc:
91
+ raise SyncError(f"无法读取原 XLSM 的 VBA,已中止导出以避免丢失宏:{exc}") from exc
92
+ try:
93
+ if "xl/vbaProject.bin" not in workbook.vba_archive.namelist():
94
+ raise SyncError("原 XLSM 中未找到 VBA 工程,无法确认宏可保留,已中止导出。")
95
+ for worksheet in list(workbook._sheets):
96
+ workbook.remove(worksheet)
97
+ workbook.create_sheet()
98
+ workbook.defined_names.clear()
99
+ return workbook
100
+ except Exception:
101
+ workbook.close()
102
+ workbook.vba_archive.close()
103
+ raise
104
+
105
+
106
+ def cmd_export(args) -> int:
107
+ docx_path = resolve_docx(args.docx)
108
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
109
+ if not args.dry_run:
110
+ check_file_free(docx_path, args.force)
111
+ check_file_free(xlsx_path, args.force)
112
+
113
+ doc = docx.Document(str(docx_path))
114
+ items = body_items(doc)
115
+ infos = [collect_table_info(doc, items, idx, tab) for idx, tab in enumerate(doc.tables)]
116
+ dedupe_table_names(infos)
117
+ recorded = {
118
+ code: name
119
+ for code, name in read_recorded_bookmarks(xlsx_path).items()
120
+ if name not in (NEW_BOOKMARK, DELETED_BOOKMARK)
121
+ }
122
+ ws_old, blocks_old = _load_previous_workbook(xlsx_path)
123
+ previous_marks = read_previous_marks(xlsx_path)
124
+ marks = find_marks(doc)
125
+ processed = processed_marks(doc, {mark.bookmark for mark in marks if mark.bookmark})
126
+ ph_fields = scan_placeholders(doc)
127
+ ph_values_old = {}
128
+ if ph_fields and xlsx_path.exists():
129
+ try:
130
+ ph_values_old = read_placeholder_values(xlsx_path, resolve_formulas=False)
131
+ except Exception as exc: # 旧工作簿读不了时不影响导出,只是带不过来已填值
132
+ log(f"[提醒] 读取原「{VALUES_SHEET}」表失败({exc}),本次无法保留已填值。")
133
+
134
+ plan = plan_table_bookmarks(doc, ws_old, blocks_old, recorded, name_unmatched=True)
135
+ name_by_index = {index: name for index, name in plan["assignments"]}
136
+ for info in infos:
137
+ info["bookmark"] = name_by_index.get(info["index"], "")
138
+
139
+ log(f"读取 Word:{docx_path.name}")
140
+ log(f"发现表格:{len(infos)} 张" + ("(无表格,工作表「" + SHEET_NAME + "」将为空)" if not infos else ""))
141
+ with_links = not getattr(args, "no_excel_links", False)
142
+ for info in infos:
143
+ log(
144
+ f" {info['code']} {info['name']}({info['nrows']} 行 × {info['ncols']} 列,"
145
+ f"合并区 {sum(1 for m in info['merges'] if m[2] > 1 or m[3] > 1)} 处,书签 {info['bookmark']})"
146
+ )
147
+ log(f"目标工作簿:{xlsx_path.name}(工作表:{SHEET_NAME})")
148
+ log(f"高亮标记:{len(marks)} 处(将写入工作表「{SHEET_MARKS}」)")
149
+ if ph_fields:
150
+ log(f"正文占位符:{len(ph_fields)} 个(将写入工作表「{VALUES_SHEET}」)")
151
+ else:
152
+ log(f"正文占位符:未发现(工作表「{VALUES_SHEET}」将为空)")
153
+ for hint in _removed_block_hints(xlsx_path, recorded, blocks_old, plan):
154
+ log(hint)
155
+
156
+ if args.dry_run:
157
+ log("预演模式(--dry-run):以上为将导出的内容,未写入任何文件。")
158
+ return 0
159
+
160
+ assignments, remove_names = split_bookmark_updates(doc, plan["assignments"], recorded)
161
+ result = apply_table_bookmarks(doc, assignments, remove_names)
162
+ if result["inserted"]:
163
+ log(f"[书签] 已把 {result['inserted']} 个书签整表锚定(点击可选中整张表格)")
164
+ created_marks = ensure_mark_bookmarks(doc, marks)
165
+ if created_marks:
166
+ log(f"[标记] 已为 {created_marks} 处高亮标记插入定位书签(MRK_xxxx,正文外观不变)")
167
+ removed_markers = cleanup_excel_markers(doc)
168
+ if removed_markers:
169
+ log(f"[清理] 已删除 Word 正文中遗留的 {removed_markers} 处 {EXCEL_LINK_TEXT} 文字/断链")
170
+
171
+ workbook = export_workbook(
172
+ infos, docx_path.name, with_links=with_links,
173
+ totals_formula=not getattr(args, "no_total_formulas", False),
174
+ wb=_empty_export_workbook(xlsx_path),
175
+ )
176
+ if ws_old is not None:
177
+ carried = carry_over_deleted_blocks(workbook, ws_old, blocks_old)
178
+ if carried:
179
+ log(f"[保留] 已可逆删除的 {len(carried)} 个表块原样保留({'、'.join(carried)}),可在「删除空白表格」页恢复。")
180
+ from ..sort_rules import carry_over_sort_settings
181
+
182
+ sort_carried = carry_over_sort_settings(workbook, ws_old, blocks_old)
183
+ if sort_carried:
184
+ log(f"[保留] {len(sort_carried)} 个表块的排序设置已按书签沿用({'、'.join(sort_carried)})。")
185
+ mark_stats = build_marks_sheet(workbook, docx_path.name, marks, previous_marks, processed)
186
+ log(
187
+ f"[标记] 工作表「{SHEET_MARKS}」已写入 {mark_stats['marks']} 行"
188
+ + (f",{mark_stats['processed']} 行已处理" if mark_stats.get("processed") else "")
189
+ + (f",另有 {mark_stats['orphans']} 行已删除记录" if mark_stats["orphans"] else "")
190
+ )
191
+ if ph_fields:
192
+ ws_ph = init_placeholder_sheet(workbook)
193
+ for field in ph_fields:
194
+ ws_ph.append([field, ph_values_old.get(field, ""), "全量"])
195
+ kept = sum(1 for f in ph_fields if ph_values_old.get(f))
196
+ log(
197
+ f"[占位符] 工作表「{VALUES_SHEET}」已写入 {len(ph_fields)} 个字段"
198
+ + (f",保留已填值 {kept} 个" if kept else "(待填写)")
199
+ )
200
+ else:
201
+ init_placeholder_sheet(workbook)
202
+ log(f"[占位符] 正文无 {{字段名}},工作表「{VALUES_SHEET}」已创建为空表。")
203
+ backup = getattr(args, "backup", True)
204
+ if not backup:
205
+ log("[导出] 按选项不备份原文件(--no-backup / 界面取消勾选),直接覆盖。")
206
+ update_docx = bool(result["removed"] or result["inserted"] or created_marks or removed_markers)
207
+ try:
208
+ backups = save_docx_xlsx_transaction(
209
+ docx_path=docx_path if update_docx else None,
210
+ doc=doc if update_docx else None,
211
+ xlsx_path=xlsx_path, wb=workbook, backup=backup,
212
+ )
213
+ finally:
214
+ workbook.close()
215
+ if getattr(workbook, "vba_archive", None):
216
+ workbook.vba_archive.close()
217
+ xlsx_backup = backups.get(xlsx_path)
218
+ log(f"[导出] 已写入 {xlsx_path.name}" + (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else ""))
219
+ if update_docx:
220
+ docx_backup = backups.get(docx_path)
221
+ log(f"[导出] 已更新 {docx_path.name}" + (f"(原文件已备份:{docx_backup.name})" if docx_backup else ""))
222
+ else:
223
+ log("[导出] Word 中的书签已是目标状态,无需改动。")
224
+ return 0
225
+
226
+
227
+ def cmd_rejudge(args) -> int:
228
+ """按工作簿当前内容重新判定 B 列表头/✓/✕(只改标记,不改数据、不改 Word)。"""
229
+ docx_path = resolve_docx(args.docx)
230
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
231
+ if not xlsx_path.exists():
232
+ raise SyncError(f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」。")
233
+ if not args.dry_run:
234
+ check_file_free(xlsx_path, args.force)
235
+ workbook = load_workbook_for_save(xlsx_path)
236
+ sheets = [(name, workbook[name]) for name in (SHEET_NAME, SHEET_NEW_TABLES) if name in workbook.sheetnames]
237
+ if not sheets:
238
+ raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
239
+ total_changed = total_rows = total_blocks = 0
240
+ old_codes: list[str] = []
241
+ for sheet_name, ws in sheets:
242
+ _, sheet_blocks = parse_blocks(ws)
243
+ total_blocks += len(sheet_blocks)
244
+ if sheet_blocks:
245
+ stats = rejudge_marks(ws, sheet_blocks)
246
+ total_changed += stats["changed"]
247
+ total_rows += stats["rows"]
248
+ old_codes.extend(stats["old"])
249
+ if not total_blocks:
250
+ raise SyncError("工作簿中没有表块,请先执行「导出表格到 Excel」")
251
+ log(f"读取工作簿:{xlsx_path.name}({len(sheets)} 个表格工作表,{total_rows} 行)")
252
+ if old_codes:
253
+ log(
254
+ f"[提醒] {'、'.join(old_codes)} 为旧布局(没有标记列),无法重新判定;"
255
+ "请执行一次「导出表格到 Excel」升级为新布局。"
256
+ )
257
+ prefix = "[判定·预演]" if args.dry_run else "[判定]"
258
+ log(f"{prefix} 重新判定 {total_rows} 行,标记变化 {total_changed} 行(表头/✓/✕;「已删」行保持原样)")
259
+ if args.dry_run:
260
+ log("预演模式(--dry-run):未写入任何文件。")
261
+ return 0
262
+ if not total_changed:
263
+ log("标记与当前内容一致,工作簿无需写入。")
264
+ return 0
265
+ backups = save_docx_xlsx_transaction(
266
+ xlsx_path=xlsx_path, wb=workbook, backup=getattr(args, "backup", True),
267
+ )
268
+ xlsx_backup = backups.get(xlsx_path)
269
+ log(f"[判定] 已保存 {xlsx_path.name}" + (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else ""))
270
+ return 0