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
@@ -10,30 +10,24 @@ from copy import deepcopy
10
10
 
11
11
  import docx
12
12
  from docx.oxml.ns import qn
13
- from openpyxl import load_workbook
14
13
  from openpyxl.styles import Alignment, Font
15
14
 
16
- from ..config import DELETED_BOOKMARK, EXCEL_LINK_TEXT, FILL_CODE_COLUMN, FONT_NAME, FONT_SIZE, MARK_DELETED, MARK_NO, NEW_BOOKMARK, SHEET_NAME
15
+ from ..config import DELETED_BOOKMARK, EXCEL_LINK_TEXT, FILL_CODE_COLUMN, FONT_NAME, FONT_SIZE, MARK_DELETED, MARK_NO, NEW_BOOKMARK, SHEET_NAME, SHEET_NEW_TABLES
17
16
  from ..console import flush_log_summary, log, log_change, warn
18
17
  from ..align import align_blocks_to_tables
19
18
  from ..changelog import export_changelog
20
19
  from ..docx_bookmarks import (
21
- bookmark_names,
22
20
  cleanup_excel_markers,
23
- insert_table_bookmark,
24
- new_cpah_name,
25
- next_bookmark_id,
26
21
  table_index_map_by_bookmark,
27
22
  unclaimed_table_indices,
28
23
  )
29
24
  from ..docx_columns import sync_columns
30
25
  from ..docx_edit import set_cell_text
31
- from ..docx_grid import body_items, build_cellmap, para_first_run_rpr, text_grid
26
+ from ..docx_grid import body_items, build_cellmap, header_rows, para_first_run_rpr, text_grid
32
27
  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
28
  from ..docx_rows import align_rows
35
29
  from ..errors import SyncError
36
- from ..excel_blocks import block_merges, parse_blocks, refresh_anchor_metadata, refresh_defined_names
30
+ from ..excel_blocks import parse_blocks, refresh_anchor_metadata, refresh_defined_names
37
31
  from ..fsops import check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx, save_docx_xlsx_transaction
38
32
  from ..sort_rules import apply_block_sort
39
33
  from ..valuefmt import display_cell, evaluate_formula, formula_map
@@ -49,17 +43,17 @@ def _block_label(block: dict, limit: int = 30) -> str:
49
43
  return text if len(text) <= limit else text[: limit - 1] + "…"
50
44
 
51
45
 
52
- def _new_table_grid(ws, block: dict, cached) -> list[list[str]]:
46
+ def _new_table_grid(ws, block: dict, cached, zero_mode: str = "excel") -> list[list[str]]:
53
47
  """新表块的网格显示文本(公式取缓存或轻量求值,与回写口径一致)。"""
54
48
  grid = []
55
49
  col0 = block.get("col0", 2)
56
- for xlsx_row in block["grid_rows"]:
50
+ for grid_index, xlsx_row in enumerate(block["grid_rows"]):
57
51
  row_texts = []
58
52
  for c in range(block["ncols"]):
59
53
  cell = ws.cell(xlsx_row, col0 + c)
60
54
  raw = cell.value
61
55
  if isinstance(raw, str) and raw.startswith("="):
62
- value = cached.get((xlsx_row, col0 + c))
56
+ value = cached.get((ws.title, xlsx_row, col0 + c))
63
57
  if value is None:
64
58
  value = evaluate_formula(ws, xlsx_row, col0 + c, cached)
65
59
  if value is None:
@@ -68,73 +62,16 @@ def _new_table_grid(ws, block: dict, cached) -> list[list[str]]:
68
62
  f"(支持 SUM 与简单四则运算)。请先在 Excel 中打开并保存该文件后再回写"
69
63
  )
70
64
  raw = value
71
- row_texts.append(display_cell(cell, raw))
65
+ row_texts.append(
66
+ display_cell(cell, raw) if grid_index == 0 else display_cell(cell, raw, zero_mode=zero_mode)
67
+ )
72
68
  grid.append(row_texts)
73
69
  return grid
74
70
 
75
71
 
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:
72
+ def _sync_table(
73
+ code: str, block: dict, tbl, ws, cached, recorder=None, name: str = "", zero_mode: str = "excel"
74
+ ) -> dict:
138
75
  """同步一张表(列结构 → 行结构 → 单元格内容),返回改动统计。
139
76
 
140
77
  recorder 不为 None 时,把逐格改动与结构改动收集为留痕记录(供导出清单/差异表)。
@@ -165,6 +102,7 @@ def _sync_table(code: str, block: dict, tbl, ws, cached, recorder=None, name: st
165
102
  "old": "", "new": ""})
166
103
 
167
104
  trs, cellmap, ncols = build_cellmap(tbl)
105
+ headers = header_rows(trs) or {0}
168
106
  if len(trs) != len(block["grid_rows"]):
169
107
  raise SyncError(f"{code}:行数对齐失败,Word 现有 {len(trs)} 行,Excel 为 {len(block['grid_rows'])} 行")
170
108
  if ncols != len(include):
@@ -194,7 +132,7 @@ def _sync_table(code: str, block: dict, tbl, ws, cached, recorder=None, name: st
194
132
  continue
195
133
  raw = cell.value
196
134
  if isinstance(raw, str) and raw.startswith("="):
197
- cached_value = cached.get((xlsx_row, col0 + excel_col))
135
+ cached_value = cached.get((ws.title, xlsx_row, col0 + excel_col))
198
136
  if cached_value is None:
199
137
  cached_value = evaluate_formula(ws, xlsx_row, col0 + excel_col, cached)
200
138
  if cached_value is None:
@@ -203,7 +141,7 @@ def _sync_table(code: str, block: dict, tbl, ws, cached, recorder=None, name: st
203
141
  f"(支持 SUM 与简单四则运算)。请先在 Excel 中打开并保存该文件后再回写"
204
142
  )
205
143
  raw = cached_value
206
- text = display_cell(cell, raw)
144
+ text = display_cell(cell, raw) if r in headers else display_cell(cell, raw, zero_mode=zero_mode)
207
145
  if pos is None or not pos.owner:
208
146
  if text.strip():
209
147
  warn(
@@ -233,6 +171,7 @@ def _sync_table(code: str, block: dict, tbl, ws, cached, recorder=None, name: st
233
171
 
234
172
 
235
173
  def cmd_writeback(args) -> int:
174
+ zero_mode = getattr(args, "table_zero", "excel")
236
175
  docx_path = resolve_docx(args.docx)
237
176
  xlsx_path = resolve_xlsx(docx_path, args.excel)
238
177
  if not xlsx_path.exists():
@@ -241,15 +180,34 @@ def cmd_writeback(args) -> int:
241
180
  check_file_free(docx_path, args.force)
242
181
  check_file_free(xlsx_path, args.force)
243
182
 
244
- doc = docx.Document(str(docx_path))
245
- wb = load_workbook_for_save(xlsx_path)
183
+ doc = getattr(args, "_doc", None)
184
+ if doc is None:
185
+ doc = docx.Document(str(docx_path))
186
+ wb = getattr(args, "_wb", None)
187
+ if wb is None:
188
+ wb = load_workbook_for_save(xlsx_path)
246
189
  if SHEET_NAME not in wb.sheetnames:
247
190
  raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
248
191
  ws = wb[SHEET_NAME]
249
- cached = formula_map(xlsx_path)
192
+ cached = getattr(args, "_formula_cache", None)
193
+ if cached is None:
194
+ cached = formula_map(xlsx_path)
250
195
  recorder: list[dict] = []
251
196
 
252
197
  order, blocks = parse_blocks(ws)
198
+ base_codes = set(order)
199
+ for sheet_name in (SHEET_NEW_TABLES,):
200
+ if sheet_name not in wb.sheetnames:
201
+ continue
202
+ extra_order, extra_blocks = parse_blocks(wb[sheet_name])
203
+ duplicate = set(extra_order) & set(order)
204
+ if duplicate:
205
+ raise SyncError(f"工作簿中表编号重复:{'、'.join(sorted(duplicate))}。")
206
+ order.extend(extra_order)
207
+ blocks.update(extra_blocks)
208
+ for code, block in blocks.items():
209
+ block["sheet_name"] = SHEET_NAME if code in base_codes else SHEET_NEW_TABLES
210
+ block["_ws"] = wb[block["sheet_name"]]
253
211
  if not order:
254
212
  raise SyncError("工作簿里没有识别到任何表块,请确认该文件由本工具导出")
255
213
 
@@ -264,7 +222,8 @@ def cmd_writeback(args) -> int:
264
222
  for code in order:
265
223
  if not recorded.get(code) or recorded[code] in (NEW_BOOKMARK, DELETED_BOOKMARK):
266
224
  continue
267
- stats = apply_block_sort(ws, blocks[code], cached, dry_run=args.dry_run)
225
+ block_ws = blocks[code]["_ws"]
226
+ stats = apply_block_sort(block_ws, blocks[code], cached, dry_run=args.dry_run)
268
227
  if stats and not args.dry_run:
269
228
  sort_changed += 1
270
229
 
@@ -272,25 +231,9 @@ def cmd_writeback(args) -> int:
272
231
  if delete_cross and all(blocks[c].get("col0", 2) == 2 for c in order):
273
232
  log("[提示] 该工作簿为旧布局(无 B 列标记),「删除✕行」本次不生效;重新导出后即可使用。")
274
233
 
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": ""})
234
+ for code in order:
235
+ if recorded.get(code) == NEW_BOOKMARK:
236
+ warn(f"{code}:旧版「书签:新增」表块已停用,请在 Word 中插入表格后重新执行「增量导出」。")
294
237
 
295
238
  items = body_items(doc)
296
239
  infos = [collect_table_info(doc, items, idx, tab) for idx, tab in enumerate(doc.tables)]
@@ -327,7 +270,7 @@ def cmd_writeback(args) -> int:
327
270
  log(f"[清理] 已删除 Word 正文中遗留的 {marker_removed} 处 {EXCEL_LINK_TEXT} 文字/断链")
328
271
 
329
272
  log(f"读取 Word:{docx_path.name}({len(doc.tables)} 张表)")
330
- log(f"读取 Excel:{xlsx_path.name}(工作表:{SHEET_NAME},{len(order)} 个表块)")
273
+ log(f"读取 Excel:{xlsx_path.name}(工作表:{SHEET_NAME}" + (f"+{SHEET_NEW_TABLES}" if SHEET_NEW_TABLES in wb.sheetnames else "") + f",{len(order)} 个表块)")
331
274
  if args.dry_run:
332
275
  log("预演模式(--dry-run):只显示将发生的改动,不写入文件。")
333
276
 
@@ -343,10 +286,13 @@ def cmd_writeback(args) -> int:
343
286
 
344
287
  for code in order:
345
288
  block = blocks[code]
289
+ block_ws = block["_ws"]
346
290
  bookmark = recorded[code]
347
291
  label = _block_label(block)
348
292
  if bookmark == NEW_BOOKMARK:
349
- continue # 新增块的预演已在前面单独列出
293
+ skipped_codes.append(code)
294
+ log(f"[跳过] {code} {label}:旧版「书签:新增」表块已停用,请改用「增量导出」")
295
+ continue
350
296
  if bookmark == DELETED_BOOKMARK:
351
297
  skipped_codes.append(code)
352
298
  log(f"[跳过] {code} {label}:已可逆删除(Excel 保留表块,可在「删除空白表格」页恢复)")
@@ -377,15 +323,15 @@ def cmd_writeback(args) -> int:
377
323
  if delete_cross and block.get("col0", 2) == 3:
378
324
  cross_rows = [
379
325
  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("合计")
326
+ if str(block_ws.cell(r, 2).value or "").strip() == MARK_NO
327
+ and not display_cell(block_ws.cell(r, 3)).strip().startswith("合计")
382
328
  ]
383
329
  if cross_rows:
384
330
  sync_block = {**block, "grid_rows": [r for r in block["grid_rows"] if r not in cross_rows]}
385
331
  remaining_body = [
386
332
  r for r in block["grid_rows"][1:]
387
333
  if r not in cross_rows
388
- and not display_cell(ws.cell(r, 3)).strip().startswith("合计")
334
+ and not display_cell(block_ws.cell(r, 3)).strip().startswith("合计")
389
335
  ]
390
336
  if not remaining_body:
391
337
  warn(
@@ -393,7 +339,7 @@ def cmd_writeback(args) -> int:
393
339
  f"之后改回✓恢复时因无数据行可复制格式会跳过该表,需先在 Word 手工补一行或从备份回滚。"
394
340
  )
395
341
  items_text = "、".join(
396
- (display_cell(ws.cell(r, 3)).strip() or "(空行)")
342
+ (display_cell(block_ws.cell(r, 3)).strip() or "(空行)")
397
343
  for r in cross_rows
398
344
  )
399
345
  log(
@@ -402,7 +348,9 @@ def cmd_writeback(args) -> int:
402
348
  )
403
349
  recorder.append({"code": code, "name": label, "kind": "删行(✕)",
404
350
  "item": f"删除 {len(cross_rows)} 个✕行:" + items_text, "old": "", "new": ""})
405
- stats = _sync_table(code, sync_block, tbl, ws, cached, recorder=recorder, name=label)
351
+ stats = _sync_table(
352
+ code, sync_block, tbl, block_ws, cached, recorder=recorder, name=label, zero_mode=zero_mode
353
+ )
406
354
  except SyncError as exc:
407
355
  tbl.getparent().replace(tbl, tbl_snapshot)
408
356
  del recorder[recorder_len:]
@@ -412,7 +360,7 @@ def cmd_writeback(args) -> int:
412
360
  continue
413
361
  if cross_rows and not args.dry_run:
414
362
  for r in cross_rows:
415
- cell = ws.cell(r, 2)
363
+ cell = block_ws.cell(r, 2)
416
364
  cell.value = MARK_DELETED
417
365
  cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color="808080")
418
366
  cell.fill = FILL_CODE_COLUMN
@@ -431,7 +379,7 @@ def cmd_writeback(args) -> int:
431
379
  if unclaimed:
432
380
  log(f"[提示] Word 中有 {len(unclaimed)} 张表格未在工作簿中找到对应记录,已保持原样")
433
381
 
434
- if not synced_codes and not created_count and not new_codes:
382
+ if not synced_codes:
435
383
  flush_log_summary()
436
384
  log(f"没有任何表块匹配到 Word 表格,未做任何写入(共 {len(order)} 个表块,全部跳过)。")
437
385
  return 0
@@ -445,16 +393,17 @@ def cmd_writeback(args) -> int:
445
393
  # 元数据里的书签名必须沿用工作簿里记录的那个(配对依据),不能被占位名覆盖
446
394
  info = {**infos[index], "bookmark": recorded[code]}
447
395
  row = block["anchor_row"]
448
- before = [ws.cell(row, col).value for col in range(1, 6)]
396
+ block_ws = block["_ws"]
397
+ before = [block_ws.cell(row, col).value for col in range(1, 6)]
449
398
  refresh_anchor_metadata(
450
- ws,
399
+ block_ws,
451
400
  block,
452
401
  info,
453
402
  docx_path.name,
454
- with_link=block.get("meta", {}).get("link_col") is not None or code in new_codes,
403
+ with_link=block.get("meta", {}).get("link_col") is not None,
455
404
  ncols=block["ncols"],
456
405
  )
457
- after = [ws.cell(row, col).value for col in range(1, 6)]
406
+ after = [block_ws.cell(row, col).value for col in range(1, 6)]
458
407
  if before != after:
459
408
  meta_changed += 1
460
409
 
@@ -470,24 +419,31 @@ def cmd_writeback(args) -> int:
470
419
  if other_skips:
471
420
  reasons.append(f"已删除/缺少书签 {other_skips} 张")
472
421
  skip_note = f",跳过 {len(skipped_codes)} 张表({'、'.join(reasons)})" if skipped_codes else ""
473
- new_note = f",新增 {created_count} 张表" if created_count else ""
474
422
  sort_note = f",排序 {sort_changed} 张表" if sort_changed else ""
475
423
  cross_note = f",删除✕行 {total_cross} 行" if total_cross else ""
476
424
  log(
477
425
  f"合计:同步 {len(synced_codes)} 张表(改动 {total_cells} 个单元格,"
478
- f"{total_rows} 行结构,{total_columns} 列结构){new_note}{sort_note}{cross_note}{skip_note}。"
426
+ f"{total_rows} 行结构,{total_columns} 列结构){sort_note}{cross_note}{skip_note}。"
479
427
  )
480
428
 
481
429
  if args.dry_run:
482
430
  log("预演结束,未写入任何文件。")
483
431
  return 0
484
432
 
485
- docx_changed = bool(total_cells or total_rows or total_columns or marker_removed or created_count)
433
+ docx_changed = bool(total_cells or total_rows or total_columns or marker_removed)
486
434
  xlsx_changed = bool(meta_changed or name_changes or sort_changed or mark_changed)
487
435
  if not docx_changed and not xlsx_changed:
488
436
  log("Word 与 Excel 数据一致,未做任何写入。")
489
437
  return 0
490
438
 
439
+ if getattr(args, "_skip_save", False):
440
+ args._writeback_result = {
441
+ "docx_changed": docx_changed, "xlsx_changed": xlsx_changed,
442
+ "recorder": recorder, "meta_changed": meta_changed,
443
+ "name_changes": len(name_changes), "mark_changed": mark_changed,
444
+ }
445
+ return 0
446
+
491
447
  backups = save_docx_xlsx_transaction(
492
448
  docx_path=docx_path if docx_changed else None,
493
449
  doc=doc if docx_changed else None,
@@ -6,9 +6,10 @@ from openpyxl.styles import PatternFill
6
6
 
7
7
 
8
8
  SHEET_NAME = "表格汇总"
9
+ SHEET_NEW_TABLES = "新增表格"
9
10
 
10
11
 
11
- CODE_RE = re.compile(r"^T\d{2,}$")
12
+ CODE_RE = re.compile(r"^(?:T|XT)\d{2,}$")
12
13
 
13
14
 
14
15
  DATE_RE = re.compile(r"^\d{4}\s*年\s*\d{1,2}\s*月\s*\d{1,2}\s*日$")
@@ -23,7 +24,7 @@ EXCEL_LINK_TEXT = "〔→Excel〕"
23
24
  BOOKMARK_PREFIX = "Table_"
24
25
 
25
26
 
26
- # 新表标记:表块 C 列写「书签:新增」表示要在 Word 里新建这张表
27
+ # 旧版新表标记:仅用于识别并提示旧工作簿,已不再支持同步建表
27
28
  NEW_BOOKMARK = "新增"
28
29
 
29
30
  # 可逆删除标记:表块 C 列写「书签:已删除」表示 Word 里的表已删、表块保留待恢复
@@ -4,6 +4,7 @@
4
4
  因此命令行行为不受影响。
5
5
  """
6
6
 
7
+ import threading
7
8
  from typing import Callable
8
9
 
9
10
  from .config import MAX_LOG_LINES
@@ -11,6 +12,7 @@ from .config import MAX_LOG_LINES
11
12
 
12
13
  _log_state = {"shown": 0, "suppressed": 0}
13
14
  _log_sink: Callable[[str], None] | None = None
15
+ _thread_state = threading.local()
14
16
 
15
17
 
16
18
  def set_log_sink(sink: Callable[[str], None] | None) -> None:
@@ -19,6 +21,10 @@ def set_log_sink(sink: Callable[[str], None] | None) -> None:
19
21
  _log_sink = sink
20
22
 
21
23
 
24
+ def set_task_log_sink(sink: Callable[[str], None] | None) -> None:
25
+ _thread_state.sink = sink
26
+
27
+
22
28
  def reset_log_state() -> None:
23
29
  """重置逐格日志的折叠计数(每个任务开始前调用)。"""
24
30
  _log_state["shown"] = 0
@@ -26,8 +32,9 @@ def reset_log_state() -> None:
26
32
 
27
33
 
28
34
  def _emit(message: str) -> None:
29
- if _log_sink is not None:
30
- _log_sink(message)
35
+ sink = getattr(_thread_state, "sink", None) or _log_sink
36
+ if sink is not None:
37
+ sink(message)
31
38
  else:
32
39
  print(message, flush=True)
33
40
 
@@ -18,11 +18,18 @@ def bookmark_names(root) -> set[str]:
18
18
 
19
19
  def used_bookmark_ids(doc) -> set[int]:
20
20
  ids = set()
21
- for el in doc.element.body.iter():
22
- if el.tag in (qn("w:bookmarkStart"), qn("w:bookmarkEnd")):
23
- value = el.get(qn("w:id"))
24
- if value and value.lstrip("-").isdigit():
25
- ids.add(int(value))
21
+ roots = [doc.element.body]
22
+ for section in doc.sections:
23
+ roots.extend(part._element for part in (
24
+ section.header, section.footer, section.first_page_header, section.first_page_footer,
25
+ section.even_page_header, section.even_page_footer,
26
+ ) if part is not None)
27
+ for root in roots:
28
+ for el in root.iter():
29
+ if el.tag in (qn("w:bookmarkStart"), qn("w:bookmarkEnd")):
30
+ value = el.get(qn("w:id"))
31
+ if value and value.lstrip("-").isdigit():
32
+ ids.add(int(value))
26
33
  return ids
27
34
 
28
35
 
@@ -109,7 +109,7 @@ def _excel_cell_display(ws, row: int, col: int, cached=None) -> str:
109
109
  cell = ws.cell(row, col)
110
110
  value = cell.value
111
111
  if isinstance(value, str) and value.startswith("=") and cached is not None:
112
- value = cached.get((row, col))
112
+ value = cached.get((ws.title, row, col))
113
113
  return display_cell(cell, value).strip()
114
114
 
115
115