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.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -2
  3. package/cordis.patch.yml +3 -0
  4. package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
  5. package/dsh_plugins/audit-e2w/lib/index.js +114 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +41 -0
  7. package/excel_word/README.md +380 -0
  8. package/excel_word/qoder_engine.py +438 -0
  9. package/excel_word/requirements.txt +4 -0
  10. package/excel_word/wesync/__init__.py +19 -0
  11. package/excel_word/wesync/__main__.py +6 -0
  12. package/excel_word/wesync/align.py +154 -0
  13. package/excel_word/wesync/api.py +840 -0
  14. package/excel_word/wesync/backup_history.py +65 -0
  15. package/excel_word/wesync/changelog.py +58 -0
  16. package/excel_word/wesync/cli.py +173 -0
  17. package/excel_word/wesync/commands/__init__.py +8 -0
  18. package/excel_word/wesync/commands/blank_cmd.py +250 -0
  19. package/excel_word/wesync/commands/bookmark_cmd.py +115 -0
  20. package/excel_word/wesync/commands/clear_cmd.py +48 -0
  21. package/excel_word/wesync/commands/export_cmd.py +220 -0
  22. package/excel_word/wesync/commands/marks_cmd.py +152 -0
  23. package/excel_word/wesync/commands/placeholders_cmd.py +87 -0
  24. package/excel_word/wesync/commands/writeback_cmd.py +513 -0
  25. package/excel_word/wesync/config.py +96 -0
  26. package/excel_word/wesync/console.py +78 -0
  27. package/excel_word/wesync/docx_blank.py +156 -0
  28. package/excel_word/wesync/docx_bookmarks.py +287 -0
  29. package/excel_word/wesync/docx_columns.py +257 -0
  30. package/excel_word/wesync/docx_edit.py +77 -0
  31. package/excel_word/wesync/docx_grid.py +212 -0
  32. package/excel_word/wesync/docx_marks.py +291 -0
  33. package/excel_word/wesync/docx_meta.py +157 -0
  34. package/excel_word/wesync/docx_newtable.py +220 -0
  35. package/excel_word/wesync/docx_placeholders.py +161 -0
  36. package/excel_word/wesync/docx_rows.py +67 -0
  37. package/excel_word/wesync/errors.py +5 -0
  38. package/excel_word/wesync/excel_blocks.py +543 -0
  39. package/excel_word/wesync/excel_export.py +136 -0
  40. package/excel_word/wesync/excel_marks.py +193 -0
  41. package/excel_word/wesync/excel_totals.py +53 -0
  42. package/excel_word/wesync/fsops.py +214 -0
  43. package/excel_word/wesync/gui/__init__.py +34 -0
  44. package/excel_word/wesync/gui/__main__.py +6 -0
  45. package/excel_word/wesync/gui/app.py +399 -0
  46. package/excel_word/wesync/gui/manual.py +68 -0
  47. package/excel_word/wesync/gui/pages/__init__.py +31 -0
  48. package/excel_word/wesync/gui/pages/_page.py +89 -0
  49. package/excel_word/wesync/gui/pages/batch_page.py +423 -0
  50. package/excel_word/wesync/gui/pages/blank_page.py +465 -0
  51. package/excel_word/wesync/gui/pages/bookmark_page.py +37 -0
  52. package/excel_word/wesync/gui/pages/export_page.py +88 -0
  53. package/excel_word/wesync/gui/pages/format_page.py +429 -0
  54. package/excel_word/wesync/gui/pages/help_page.py +92 -0
  55. package/excel_word/wesync/gui/pages/history_page.py +145 -0
  56. package/excel_word/wesync/gui/pages/marks_page.py +178 -0
  57. package/excel_word/wesync/gui/pages/writeback_page.py +452 -0
  58. package/excel_word/wesync/gui/resources.py +22 -0
  59. package/excel_word/wesync/gui/runner.py +74 -0
  60. package/excel_word/wesync/gui/store.py +34 -0
  61. package/excel_word/wesync/gui/theme.py +100 -0
  62. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  63. package/excel_word/wesync/gui/widgets/cards.py +20 -0
  64. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  65. package/excel_word/wesync/gui/widgets/logpane.py +110 -0
  66. package/excel_word/wesync/gui/widgets/nav.py +39 -0
  67. package/excel_word/wesync/report_format.py +1577 -0
  68. package/excel_word/wesync/sort_rules.py +244 -0
  69. package/excel_word/wesync/valuefmt.py +462 -0
  70. package/package.json +49 -4
  71. package/qoder_plugins/audit-toolbox/README.md +156 -0
  72. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,543 @@
1
+ """Excel 解析层:识别表块与锚点元数据、刷新书签名/链接/列数、刷新 EX_ 定义名称。"""
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from openpyxl.styles import Alignment, Font
6
+ from openpyxl.utils import get_column_letter
7
+ from openpyxl.workbook.defined_name import DefinedName
8
+ from openpyxl.worksheet.hyperlink import Hyperlink
9
+ from .config import CODE_RE, DELETED_BOOKMARK, FILL_ANCHOR, FILL_CODE_COLUMN, FONT_NAME, FONT_SIZE, MARK_DELETED, MARK_HEADER, MARK_NO, MARK_VALUES, MARK_YES, META_SCAN_COLUMNS, NEW_BOOKMARK, SHEET_NAME
10
+ from .console import log, warn
11
+ from .fsops import backup_file, load_workbook_for_save
12
+
13
+
14
+ def _cell_str(ws, row: int, col: int) -> str:
15
+ value = ws.cell(row, col).value
16
+ if value is None:
17
+ return ""
18
+ return str(value).strip()
19
+
20
+
21
+ def _merged_ranges(ws) -> list[tuple[int, int, int, int]]:
22
+ return [(r.min_row, r.min_col, r.max_row, r.max_col) for r in ws.merged_cells.ranges]
23
+
24
+
25
+ def _in_merged(ranges, row: int, col: int) -> bool:
26
+ return any(r1 <= row <= r2 and c1 <= col <= c2 for (r1, c1, r2, c2) in ranges)
27
+
28
+
29
+ def row_grid_has_content(ws, row: int, max_col: int, ranges, start_col: int = 2) -> bool:
30
+ for col in range(start_col, max(max_col, start_col) + 1):
31
+ cell = ws.cell(row, col)
32
+ if cell.value is not None and str(cell.value).strip() != "":
33
+ return True
34
+ if _in_merged(ranges, row, col):
35
+ return True
36
+ return False
37
+
38
+
39
+ def anchor_metadata(ws, row: int, max_col: int) -> dict:
40
+ """按内容特征定位锚点行的元数据,兼容插入列后整体右移的情况。"""
41
+ meta: dict = {"name": "", "bookmark": "", "ncols": None, "link_col": None, "after": "", "restore_after": "", "caption": "", "sort": "", "cols": {}}
42
+ for col in range(1, min(max_col, META_SCAN_COLUMNS) + 1):
43
+ cell = ws.cell(row, col)
44
+ text = "" if cell.value is None else str(cell.value).strip()
45
+ if col > 1 and cell.hyperlink is not None and meta["link_col"] is None:
46
+ meta["link_col"] = col
47
+ meta["cols"]["link"] = col
48
+ if text.startswith("书签:"):
49
+ meta["cols"]["bookmark"] = col
50
+ meta["bookmark"] = text.split(":", 1)[1].split("(", 1)[0].strip()
51
+ elif col >= 2 and text in (NEW_BOOKMARK, "新表"):
52
+ meta["cols"]["bookmark"] = col
53
+ meta["bookmark"] = NEW_BOOKMARK
54
+ elif text.startswith("列数:"):
55
+ meta["cols"]["ncols"] = col
56
+ match = re.search(r"(\d+)", text)
57
+ if match:
58
+ meta["ncols"] = int(match.group(1))
59
+ elif col >= 2 and text.startswith("位置:"):
60
+ meta["cols"]["pos"] = col
61
+ value = text.split(":", 1)[1].strip()
62
+ match = re.match(r"T\d{2,}", value)
63
+ meta["after"] = match.group(0) if match else "末尾"
64
+ elif col >= 2 and text.startswith("原位置:"):
65
+ meta["cols"]["restore_pos"] = col
66
+ value = text.split(":", 1)[1].strip()
67
+ meta["restore_after"] = value[:-2] if value.endswith("之后") else "末尾"
68
+ elif col >= 2 and text.startswith("原标题:"):
69
+ meta["cols"]["caption"] = col
70
+ meta["caption"] = text.split(":", 1)[1].strip()
71
+ elif col >= 2 and text.startswith("排序:"):
72
+ meta["cols"]["sort"] = col
73
+ meta["sort"] = text
74
+ elif col >= 2 and not meta["name"] and ("【表" in text or text.startswith("【新表】")):
75
+ meta["cols"]["name"] = col
76
+ meta["name"] = text
77
+ return meta
78
+
79
+
80
+ def parse_blocks(ws) -> tuple[list[str], dict[str, dict]]:
81
+ """解析表块。
82
+
83
+ 块归属规则:A 列为表编号的行、以及 A 列为空但网格区有内容的行(例如用户在块中间
84
+ 插入行后直接填数据)都计入当前表块;整行空白视为分隔行,不计入行数。
85
+ """
86
+ order: list[str] = []
87
+ blocks: dict[str, dict] = {}
88
+ max_row = ws.max_row or 0
89
+ max_col = ws.max_column or 0
90
+ ranges = _merged_ranges(ws)
91
+ current: dict | None = None
92
+
93
+ for row in range(1, max_row + 1):
94
+ code = _cell_str(ws, row, 1)
95
+ if CODE_RE.match(code):
96
+ if current is not None and current["code"] == code:
97
+ if current["col0"] == 3 and _cell_str(ws, row, 2) == MARK_DELETED:
98
+ continue # 「已删」墓碑行不计入网格
99
+ current["grid_rows"].append(row) # 块内数据行同样带表编号
100
+ continue
101
+ meta = anchor_metadata(ws, row, max_col)
102
+ current = {
103
+ "code": code,
104
+ "anchor_row": row,
105
+ "grid_rows": [],
106
+ "meta": meta,
107
+ "col0": 3 if meta["cols"].get("name") == 3 else 2,
108
+ }
109
+ blocks[code] = current
110
+ order.append(code)
111
+ continue
112
+ if current is None or code != "":
113
+ continue
114
+ if current["col0"] == 3 and _cell_str(ws, row, 2) == MARK_DELETED:
115
+ continue
116
+ if row_grid_has_content(ws, row, max_col, ranges, start_col=current["col0"]):
117
+ current["grid_rows"].append(row)
118
+
119
+ for block in blocks.values():
120
+ head_mark = _cell_str(ws, block["grid_rows"][0], 2) if block["grid_rows"] else ""
121
+ second_mark = _cell_str(ws, block["grid_rows"][1], 2) if len(block["grid_rows"]) > 1 else ""
122
+ if block["col0"] == 2 and head_mark in MARK_VALUES and second_mark in (MARK_YES, MARK_NO, MARK_DELETED):
123
+ block["col0"] = 3
124
+ col0 = block["col0"]
125
+ inferred = 0
126
+ for grid_row in block["grid_rows"]:
127
+ for col in range(max(max_col, 2), 1, -1):
128
+ cell = ws.cell(grid_row, col)
129
+ filled = cell.value is not None and str(cell.value).strip() != ""
130
+ # 空格子但带格式,说明它属于导出的网格(例如整列为空的表格列)
131
+ if filled or cell.has_style or _in_merged(ranges, grid_row, col):
132
+ inferred = max(inferred, col - col0 + 1)
133
+ break
134
+ block["ncols"] = inferred
135
+ block["bookmark"] = block["meta"].get("bookmark", "")
136
+ block["is_new"] = block["bookmark"] == NEW_BOOKMARK
137
+ if block["is_new"]:
138
+ # 新表块要按"连续网格"取行:空但有样式的行(模板/Excel 插入行)也算表格行
139
+ declared = block["meta"].get("ncols")
140
+ ncols = declared or inferred or 1
141
+ rows = []
142
+ row = block["anchor_row"] + 1
143
+ while row <= max_row:
144
+ code_text = _cell_str(ws, row, 1)
145
+ if code_text and code_text != block["code"]:
146
+ break
147
+ if _cell_str(ws, row, 2) == MARK_DELETED:
148
+ break
149
+ has = row_grid_has_content(ws, row, max_col, ranges, start_col=col0) or any(
150
+ ws.cell(row, col).has_style for col in range(col0, col0 + ncols)
151
+ )
152
+ if not has:
153
+ break
154
+ rows.append(row)
155
+ row += 1
156
+ block["grid_rows"] = rows
157
+ block["ncols"] = declared or max(inferred, 1)
158
+ return order, blocks
159
+
160
+
161
+ def refresh_anchor_metadata(ws, block: dict, info: dict, docx_name: str, with_link: bool = True, ncols: int | None = None) -> None:
162
+ """把锚点行元数据写回规范位置(col0 名称 / +1 书签 / +2 链接 / +3 列数),并清理错位残留。"""
163
+ row = block["anchor_row"]
164
+ col0 = block.get("col0", 2)
165
+ for col in range(col0, META_SCAN_COLUMNS + 1):
166
+ if col in (col0, col0 + 1, col0 + 2, col0 + 3):
167
+ continue
168
+ cell = ws.cell(row, col)
169
+ text = "" if cell.value is None else str(cell.value).strip()
170
+ if text.startswith(("书签:", "列数:", "位置:", "原位置:", "原标题:")) or text == "→定位Word表":
171
+ cell.value = None
172
+ cell.hyperlink = None
173
+
174
+ ws.cell(row, col0, f"【表{info['index'] + 1}】{info['name']} · 章节:{info['section']}")
175
+ ws.cell(row, col0 + 1, f"书签:{info['bookmark']}")
176
+ link_cell = ws.cell(row, col0 + 2, "→定位Word表")
177
+ if with_link:
178
+ link_cell.hyperlink = Hyperlink(
179
+ ref=link_cell.coordinate, target=docx_name, location=info["bookmark"], display="→定位Word表"
180
+ )
181
+ else:
182
+ link_cell.hyperlink = None
183
+ ws.cell(row, col0 + 3, f"列数:{ncols if ncols is not None else info['ncols']}")
184
+ for col in range(1, col0 + 4):
185
+ cell = ws.cell(row, col)
186
+ cell.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True, color="1F4E79")
187
+ cell.fill = FILL_ANCHOR
188
+ cell.alignment = Alignment(horizontal="left" if col > 1 else "center", vertical="center")
189
+
190
+
191
+ def refresh_defined_names(wb, blocks: dict[str, dict]) -> list[str]:
192
+ """把 EX_Tnn 重新指向各表数据区首行(用户增删行后仍能准确定位)。"""
193
+ changed = []
194
+ for code, block in blocks.items():
195
+ letter = get_column_letter(block.get("col0", 2))
196
+ ref = f"'{SHEET_NAME}'!${letter}${block['anchor_row'] + 1}"
197
+ name = f"EX_{code}"
198
+ existing = wb.defined_names.get(name) if hasattr(wb.defined_names, "get") else None
199
+ if existing is not None and existing.attr_text == ref:
200
+ continue
201
+ definition = DefinedName(name, attr_text=ref)
202
+ try:
203
+ wb.defined_names.add(definition)
204
+ except AttributeError:
205
+ wb.defined_names[name] = definition
206
+ changed.append(f"{name} → {ref}")
207
+ return changed
208
+
209
+
210
+ def read_recorded_bookmarks(xlsx_path: Path) -> dict[str, str]:
211
+ """读取现有工作簿里记录的表编号 → 书签名,用于复用既有书签。"""
212
+ if not xlsx_path.exists():
213
+ return {}
214
+ try:
215
+ wb = load_workbook_for_save(xlsx_path)
216
+ except Exception as exc: # 文件被占用或损坏时不阻断主流程
217
+ warn(f"读取现有工作簿失败({exc}),本次不沿用旧书签名")
218
+ return {}
219
+ if SHEET_NAME not in wb.sheetnames:
220
+ return {}
221
+ _, blocks = parse_blocks(wb[SHEET_NAME])
222
+ return {code: block.get("bookmark", "") for code, block in blocks.items() if block.get("bookmark")}
223
+
224
+
225
+ def block_merges(ws, block: dict) -> list[tuple[int, int, int, int]]:
226
+ """表块网格内的 Excel 合并区 → (起始行, 起始列, 行跨度, 列跨度),坐标相对块内网格。"""
227
+ rows = block["grid_rows"]
228
+ if not rows:
229
+ return []
230
+ row_index = {r: i for i, r in enumerate(rows)}
231
+ ncols = block["ncols"]
232
+ col0 = block.get("col0", 2)
233
+ result = []
234
+ for (r1, c1, r2, c2) in _merged_ranges(ws):
235
+ if c1 < col0 or c1 > col0 - 1 + ncols or r1 not in row_index or r2 not in row_index:
236
+ continue
237
+ c2 = min(c2, col0 - 1 + ncols)
238
+ result.append((row_index[r1], c1 - col0, row_index[r2] - row_index[r1] + 1, c2 - c1 + 1))
239
+ return result
240
+
241
+
242
+ _CELL_REF_IN_FORMULA_RE = re.compile(r"(?<![A-Za-z0-9_$])(\$?[A-Za-z]{1,3}\$?)(\d+)")
243
+
244
+
245
+ def _shift_formula(text: str, idx: int, amount: int) -> str:
246
+ """按 Excel 插行语义平移公式里的行号:引用行 >= idx 的加 amount(引号内文本不动)。"""
247
+
248
+ parts = re.split(r'("[^"]*")', text)
249
+ for i, part in enumerate(parts):
250
+ if part.startswith('"'):
251
+ continue
252
+
253
+ def repl(match: re.Match, part: str = part) -> str:
254
+ if part[match.end():match.end() + 1] == "(": # LOG10( 这类函数名,不是单元格引用
255
+ return match.group(0)
256
+ row = int(match.group(2))
257
+ return f"{match.group(1)}{row + amount if row >= idx else row}"
258
+
259
+ parts[i] = _CELL_REF_IN_FORMULA_RE.sub(repl, part)
260
+ return "".join(parts)
261
+
262
+
263
+ def _insert_rows_safe(ws, idx: int, amount: int) -> None:
264
+ """在 idx 行前插入 amount 行,并自行搬运合并区/超链接/公式引用/行高。
265
+
266
+ openpyxl 的 insert_rows 只搬单元格本体,这些附件不搬或搬错,必须手工处理。
267
+ """
268
+ from openpyxl.worksheet.dimensions import RowDimension
269
+
270
+ merges = _merged_ranges(ws)
271
+ for (r1, c1, r2, c2) in merges:
272
+ ws.unmerge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
273
+ heights = {
274
+ r: dim.height for r, dim in ws.row_dimensions.items() if r >= idx and dim.height is not None
275
+ }
276
+ ws.insert_rows(idx, amount)
277
+ for (r1, c1, r2, c2) in merges:
278
+ if r1 >= idx:
279
+ r1 += amount
280
+ r2 += amount
281
+ elif r2 >= idx:
282
+ r2 += amount
283
+ ws.merge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
284
+ for r in [r for r in ws.row_dimensions if r >= idx]:
285
+ del ws.row_dimensions[r]
286
+ for r, height in heights.items():
287
+ ws.row_dimensions[r + amount] = RowDimension(ws, index=r + amount, height=height, customHeight=True)
288
+ for row in ws.iter_rows():
289
+ for cell in row:
290
+ if cell.hyperlink is not None:
291
+ cell.hyperlink.ref = cell.coordinate
292
+ if isinstance(cell.value, str) and cell.value.startswith("="):
293
+ cell.value = _shift_formula(cell.value, idx, amount)
294
+
295
+
296
+ def append_new_block(wb, name: str, nrows: int, ncols: int, after: str | None = None) -> str:
297
+ """在指定表块下面物理插入一个规范的新表块(C 列带「书签:新增」标记),返回表编号。
298
+
299
+ ``after`` 指定插到哪张表下面(如 "T02"),不指定时插到最后一张表下面;
300
+ 后续表块整体下移,全部表块按上下顺序重新编号(T01、T02…依次顺延)。
301
+ Word 建表位置跟随工作簿顺序,即插在哪张表下面就建在哪张表之后。
302
+ 网格预置标准边框与字体:空行也带样式,填数后即可被回写识别为新建 Word 表。
303
+ """
304
+ from openpyxl.utils import get_column_letter
305
+ from .docx_grid import position_sides
306
+ from .errors import SyncError
307
+ from .excel_export import make_border
308
+
309
+ name = (name or "").strip()
310
+ if not name:
311
+ raise SyncError("请填写新表名称")
312
+ if not 1 <= nrows <= 200 or not 1 <= ncols <= 30:
313
+ raise SyncError("行数限 1~200、列数限 1~30")
314
+ if SHEET_NAME not in wb.sheetnames:
315
+ raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
316
+ ws = wb[SHEET_NAME]
317
+ order, blocks = parse_blocks(ws)
318
+ after = (after or "").strip()
319
+ if after and after not in order:
320
+ raise SyncError(f"插入位置 {after} 不在工作簿的表编号里,请重新选择")
321
+ if not after and order:
322
+ after = order[-1]
323
+ next_num = max([int(code[1:]) for code in order if code[1:].isdigit()] + [0]) + 1
324
+ code = f"T{next_num:02d}"
325
+
326
+ if after:
327
+ prev = blocks[after]
328
+ anchor = max([prev["anchor_row"]] + prev["grid_rows"]) + 2 # 与上一块空一行
329
+ if anchor <= (ws.max_row or 0):
330
+ _insert_rows_safe(ws, anchor, nrows + 2) # 锚点行 + 网格行 + 与下一块的空行
331
+ else:
332
+ anchor = (ws.max_row or 0) + 2
333
+ ws.cell(anchor, 1, code)
334
+ ws.cell(anchor, 3, f"【新表】{name}")
335
+ ws.cell(anchor, 4, f"书签:{NEW_BOOKMARK}")
336
+ ws.cell(anchor, 5, "→定位Word表")
337
+ ws.cell(anchor, 6, f"列数:{ncols}")
338
+ for col in range(1, 7):
339
+ cell = ws.cell(anchor, col)
340
+ cell.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True, color="1F4E79")
341
+ cell.fill = FILL_ANCHOR
342
+ cell.alignment = Alignment(horizontal="left" if col > 1 else "center", vertical="center")
343
+
344
+ borders = {"top": "thin", "bottom": "thin", "left": None, "right": None, "insideH": "dotted", "insideV": "dotted"}
345
+ for r in range(nrows):
346
+ grid_row = anchor + 1 + r
347
+ code_cell = ws.cell(grid_row, 1, code)
348
+ code_cell.fill = FILL_CODE_COLUMN
349
+ code_cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color="808080")
350
+ code_cell.alignment = Alignment(horizontal="center", vertical="center")
351
+ mark_cell = ws.cell(grid_row, 2, MARK_HEADER if r == 0 else MARK_NO)
352
+ mark_cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color="808080" if r == 0 else "C00000")
353
+ mark_cell.alignment = Alignment(horizontal="center", vertical="center")
354
+ for c in range(ncols):
355
+ cell = ws.cell(grid_row, 3 + c)
356
+ cell.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=(r == 0))
357
+ cell.border = make_border(position_sides(borders, r, c, nrows, ncols))
358
+ cell.alignment = Alignment(horizontal="center" if r == 0 else "left", vertical="center", wrap_text=True)
359
+ for c in range(ncols):
360
+ letter = get_column_letter(3 + c)
361
+ if letter not in ws.column_dimensions or not ws.column_dimensions[letter].width:
362
+ ws.column_dimensions[letter].width = 12.0
363
+
364
+ # 物理插入后按上下顺序重新编号:A 列、【表N】标签、EX_ 定义名称一起顺延
365
+ order2, blocks2 = parse_blocks(ws)
366
+ renamed: dict[str, str] = {}
367
+ final_blocks: dict[str, dict] = {}
368
+ for i, old_code in enumerate(order2, 1):
369
+ new_code = f"T{i:02d}"
370
+ block = blocks2[old_code]
371
+ renamed[old_code] = new_code
372
+ if old_code != new_code:
373
+ ws.cell(block["anchor_row"], 1, new_code)
374
+ for r in block["grid_rows"]:
375
+ ws.cell(r, 1, new_code)
376
+ label = ws.cell(block["anchor_row"], block["col0"]).value
377
+ if isinstance(label, str):
378
+ ws.cell(block["anchor_row"], block["col0"]).value = re.sub(r"【表\d+】", f"【表{i}】", label, count=1)
379
+ final_blocks[new_code] = block
380
+ for nm in list(wb.defined_names.keys()):
381
+ if nm.startswith("EX_") and nm[3:] not in final_blocks:
382
+ del wb.defined_names[nm]
383
+ refresh_defined_names(wb, final_blocks)
384
+ return renamed[code]
385
+
386
+
387
+ def rejudge_marks(ws, blocks: dict) -> dict:
388
+ """按工作簿当前内容重新判定 B 列标记(表头/✓/✕),只改标记不改数据。
389
+
390
+ 仅新布局表块(col0=3)参与:网格首行=表头;其余行除首列外任一列有内容
391
+ (含公式、「—」等占位文字)=✓,否则=✕,口径与导出时一致。
392
+ 「已删」行不在 grid_rows 里,天然保持原样。旧布局块记入 old 列表提示重新导出。
393
+ """
394
+ changed = 0
395
+ rows = 0
396
+ old: list[str] = []
397
+ for code, block in blocks.items():
398
+ if block.get("col0", 2) != 3:
399
+ old.append(code)
400
+ continue
401
+ col0, ncols = block["col0"], block["ncols"]
402
+ for i, row in enumerate(block["grid_rows"]):
403
+ rows += 1
404
+ if i == 0:
405
+ mark, color = MARK_HEADER, "808080"
406
+ else:
407
+ has = False
408
+ for c in range(1, ncols):
409
+ cell = ws.cell(row, col0 + c)
410
+ value = cell.value
411
+ if isinstance(value, str) and value.startswith("="):
412
+ has = True
413
+ break
414
+ if value is not None and str(value).strip():
415
+ has = True
416
+ break
417
+ mark, color = (MARK_YES, "008000") if has else (MARK_NO, "C00000")
418
+ mark_cell = ws.cell(row, 2)
419
+ if mark_cell.value != mark:
420
+ changed += 1
421
+ mark_cell.value = mark
422
+ mark_cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color=color)
423
+ mark_cell.alignment = Alignment(horizontal="center", vertical="center")
424
+ return {"changed": changed, "rows": rows, "old": old}
425
+
426
+
427
+ def carry_over_deleted_blocks(wb_new, ws_old, blocks_old: dict) -> list[str]:
428
+ """导出重建工作簿时,把「已可逆删除」的表块原样保留到新工作簿末尾。
429
+
430
+ 复制值、样式、合并区与锚点记录(原位置/原标题),编号顺延;返回保留的表编号。
431
+ """
432
+ from copy import copy
433
+ from openpyxl.utils import get_column_letter
434
+
435
+ deleted = [b for b in blocks_old.values() if b.get("bookmark") == DELETED_BOOKMARK]
436
+ if not deleted:
437
+ return []
438
+ ws = wb_new[SHEET_NAME]
439
+ order, _ = parse_blocks(ws)
440
+ next_num = max([int(code[1:]) for code in order if code[1:].isdigit()] + [0]) + 1
441
+ carried: list[str] = []
442
+ new_blocks: dict[str, dict] = {}
443
+ for block in deleted:
444
+ code = f"T{next_num:02d}"
445
+ next_num += 1
446
+ old_anchor = block["anchor_row"]
447
+ old_col0 = block.get("col0", 2)
448
+ anchor = (ws.max_row or 0) + 2
449
+ for col in range(1, META_SCAN_COLUMNS + 1):
450
+ old = ws_old.cell(old_anchor, col)
451
+ if old.value is None and not old.has_style:
452
+ continue
453
+ new_col = 1 if col == 1 else (col if col < old_col0 else col + 3 - old_col0)
454
+ new = ws.cell(anchor, new_col)
455
+ new.value = old.value
456
+ if old.has_style:
457
+ new._style = copy(old._style)
458
+ ws.cell(anchor, 1, code)
459
+ ws.cell(anchor, 4, f"书签:{DELETED_BOOKMARK}")
460
+ link = ws.cell(anchor, 5)
461
+ link.value = None
462
+ link.hyperlink = None
463
+ grid_rows = []
464
+ for i, old_row in enumerate(block["grid_rows"]):
465
+ new_row = anchor + 1 + i
466
+ grid_rows.append(new_row)
467
+ old = ws_old.cell(old_row, 1)
468
+ new = ws.cell(new_row, 1)
469
+ new.value = code
470
+ if old.has_style:
471
+ new._style = copy(old._style)
472
+ if old_col0 == 3:
473
+ old = ws_old.cell(old_row, 2)
474
+ new = ws.cell(new_row, 2)
475
+ new.value = old.value
476
+ if old.has_style:
477
+ new._style = copy(old._style)
478
+ for c in range(block["ncols"]):
479
+ old = ws_old.cell(old_row, old_col0 + c)
480
+ new = ws.cell(new_row, 3 + c)
481
+ new.value = old.value
482
+ if old.has_style:
483
+ new._style = copy(old._style)
484
+ for (r, c, rs, cs) in block_merges(ws_old, block):
485
+ if rs == 1 and cs == 1:
486
+ continue
487
+ ws.merge_cells(
488
+ start_row=anchor + 1 + r, start_column=3 + c,
489
+ end_row=anchor + r + rs, end_column=2 + c + cs,
490
+ )
491
+ for c in range(block["ncols"]):
492
+ old_dim = ws_old.column_dimensions.get(get_column_letter(old_col0 + c))
493
+ if old_dim is not None and old_dim.width:
494
+ letter = get_column_letter(3 + c)
495
+ cur = ws.column_dimensions[letter].width or 0
496
+ ws.column_dimensions[letter].width = max(cur, old_dim.width)
497
+ new_blocks[code] = {"code": code, "anchor_row": anchor, "grid_rows": grid_rows, "ncols": block["ncols"], "col0": 3}
498
+ carried.append(code)
499
+ refresh_defined_names(wb_new, new_blocks)
500
+ return carried
501
+
502
+
503
+ def refresh_workbook_metadata(
504
+ xlsx_path: Path,
505
+ docx_name: str,
506
+ infos_by_code: dict[str, dict],
507
+ with_links: bool = True,
508
+ ) -> int:
509
+ """刷新工作簿里的书签名、跳转链接与列数(不动任何数据单元格)。"""
510
+ wb = load_workbook_for_save(xlsx_path)
511
+ if SHEET_NAME not in wb.sheetnames:
512
+ return 0
513
+ ws = wb[SHEET_NAME]
514
+ _, blocks = parse_blocks(ws)
515
+ changed = 0
516
+ for code, block in blocks.items():
517
+ info = infos_by_code.get(code)
518
+ if info is None:
519
+ continue
520
+ row = block["anchor_row"]
521
+ col0 = block.get("col0", 2)
522
+ before = [
523
+ ws.cell(row, col).value for col in range(1, col0 + 4)
524
+ ] + [
525
+ (ws.cell(row, col0 + 2).hyperlink.location if ws.cell(row, col0 + 2).hyperlink else None)
526
+ ]
527
+ refresh_anchor_metadata(ws, block, info, docx_name, with_link=with_links, ncols=block["ncols"])
528
+ after = [
529
+ ws.cell(row, col).value for col in range(1, col0 + 4)
530
+ ] + [
531
+ (ws.cell(row, col0 + 2).hyperlink.location if ws.cell(row, col0 + 2).hyperlink else None)
532
+ ]
533
+ if before != after:
534
+ changed += 1
535
+ log(f"[定位] {code}:书签/链接已刷新为 {info['bookmark']}")
536
+ names = refresh_defined_names(wb, blocks)
537
+ if changed or names:
538
+ backup = backup_file(xlsx_path)
539
+ wb.save(str(xlsx_path))
540
+ log(f"[定位] 已保存 {xlsx_path.name}" + (f"(原文件已备份:{backup.name})" if backup else ""))
541
+ else:
542
+ log("[定位] Excel 中的书签名与链接已是目标状态,无需改动")
543
+ return changed + len(names)
@@ -0,0 +1,136 @@
1
+ """Excel 导出层:把 Word 表格生成为单工作表堆叠结构(样式、合并、跳转链接、定义名称)。"""
2
+
3
+ from openpyxl import Workbook
4
+ from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
5
+ from openpyxl.utils import get_column_letter
6
+ from openpyxl.workbook.defined_name import DefinedName
7
+ from openpyxl.worksheet.hyperlink import Hyperlink
8
+ from .config import FILL_ANCHOR, FILL_CODE_COLUMN, FONT_NAME, FONT_SIZE, MARK_HEADER, MARK_NO, MARK_YES, SHEET_NAME
9
+ from .console import log
10
+ from .docx_grid import cell_alignment, explicit_borders, position_sides
11
+ from .excel_totals import total_formula_cells
12
+ from .valuefmt import approx_width, display_text, to_excel_value
13
+
14
+
15
+ def make_border(sides: dict) -> Border:
16
+ def side(name):
17
+ style = sides.get(name)
18
+ return Side(style=style) if style else Side()
19
+
20
+ return Border(left=side("left"), right=side("right"), top=side("top"), bottom=side("bottom"))
21
+
22
+
23
+ def export_workbook(infos: list[dict], docx_name: str, with_links: bool = True, totals_formula: bool = True) -> Workbook:
24
+ wb = Workbook()
25
+ ws = wb.active
26
+ ws.title = SHEET_NAME
27
+ ws.column_dimensions["A"].width = 7
28
+ ws.freeze_panes = "A1"
29
+
30
+ widths: dict[int, float] = {}
31
+ row = 1
32
+ defined: list[tuple[str, str]] = []
33
+ formula_count = 0
34
+
35
+ for info in infos:
36
+ anchor_row = row
37
+ code = info["code"]
38
+
39
+ ws.cell(anchor_row, 1, code)
40
+ ws.cell(anchor_row, 3, f"【表{info['index'] + 1}】{info['name']} · 章节:{info['section']}")
41
+ meta_text = f"书签:{info['bookmark']}"
42
+ if info.get("old_bookmark"):
43
+ meta_text += f"(原审计软件书签:{info['old_bookmark']})"
44
+ ws.cell(anchor_row, 4, meta_text)
45
+ link_cell = ws.cell(anchor_row, 5, "→定位Word表")
46
+ if with_links:
47
+ link_cell.hyperlink = Hyperlink(
48
+ ref=link_cell.coordinate, target=docx_name, location=info["bookmark"], display="→定位Word表"
49
+ )
50
+ ws.cell(anchor_row, 6, f"列数:{info['ncols']}")
51
+ for col in range(1, 7):
52
+ cell = ws.cell(anchor_row, col)
53
+ cell.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True, color="1F4E79")
54
+ cell.fill = FILL_ANCHOR
55
+ cell.alignment = Alignment(horizontal="left" if col > 1 else "center", vertical="center")
56
+
57
+ grid_start = anchor_row + 1
58
+ nrows, ncols = info["nrows"], info["ncols"]
59
+ borders = info["borders"]
60
+ sides_cache: dict[tuple[int, int], dict] = {}
61
+ formulas = total_formula_cells(info, grid_start, col0=3) if totals_formula else {}
62
+ formula_count += len(formulas)
63
+
64
+ for r in range(nrows):
65
+ xlsx_row = grid_start + r
66
+ code_cell = ws.cell(xlsx_row, 1, code)
67
+ code_cell.fill = FILL_CODE_COLUMN
68
+ code_cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color="808080")
69
+ code_cell.alignment = Alignment(horizontal="center", vertical="center")
70
+ if r == 0:
71
+ mark, mark_color = MARK_HEADER, "808080"
72
+ else:
73
+ has_content = any((info["text"][r][c] or "").strip() for c in range(1, ncols)) or any(
74
+ (xlsx_row, 3 + c) in formulas for c in range(1, ncols)
75
+ )
76
+ mark, mark_color = (MARK_YES, "008000") if has_content else (MARK_NO, "C00000")
77
+ mark_cell = ws.cell(xlsx_row, 2, mark)
78
+ mark_cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color=mark_color)
79
+ mark_cell.alignment = Alignment(horizontal="center", vertical="center")
80
+ for c in range(ncols):
81
+ pos = info["cellmap"][r][c]
82
+ sides_cache[(r, c)] = position_sides(borders, r, c, nrows, ncols)
83
+ if pos is None or not pos.owner:
84
+ continue
85
+ cell = ws.cell(xlsx_row, 3 + c)
86
+ value, number_format = to_excel_value(info["text"][r][c] or "")
87
+ horizontal, vertical, _ = cell_alignment(pos.tc)
88
+ formula = formulas.get((xlsx_row, 3 + c))
89
+ if formula is not None:
90
+ cell.value = formula
91
+ elif value is not None:
92
+ cell.value = value
93
+ cell.number_format = number_format or ("@" if isinstance(value, str) else "General")
94
+ cell.alignment = Alignment(
95
+ horizontal=horizontal, vertical=vertical, wrap_text=True if isinstance(value, str) and "\n" in value else False
96
+ )
97
+ cell.font = Font(name=FONT_NAME, size=FONT_SIZE)
98
+ sides = dict(sides_cache[(r, c)])
99
+ sides.update(explicit_borders(pos.tc))
100
+ cell.border = make_border(sides)
101
+ text_for_width = display_text(value, number_format) if value is not None else ""
102
+ longest = max((approx_width(part) for part in text_for_width.split("\n")), default=0.0)
103
+ widths[3 + c] = max(widths.get(3 + c, 8.0), min(longest + 2.0, 45.0))
104
+
105
+ for (r, c, rowspan, colspan) in info["merges"]:
106
+ if rowspan == 1 and colspan == 1:
107
+ continue
108
+ ws.merge_cells(
109
+ start_row=grid_start + r,
110
+ start_column=3 + c,
111
+ end_row=grid_start + r + rowspan - 1,
112
+ end_column=3 + c + colspan - 1,
113
+ )
114
+ top = sides_cache[(r, c)]["top"]
115
+ left = sides_cache[(r, c)]["left"]
116
+ bottom = sides_cache[(r + rowspan - 1, c + colspan - 1)]["bottom"]
117
+ right = sides_cache[(r + rowspan - 1, c + colspan - 1)]["right"]
118
+ anchor_cell = ws.cell(grid_start + r, 3 + c)
119
+ anchor_cell.border = make_border({"top": top, "left": left, "bottom": bottom, "right": right})
120
+
121
+ defined.append((f"EX_{code}", f"'{SHEET_NAME}'!$C${grid_start}"))
122
+ row = grid_start + nrows + 1 # 表间空一行
123
+
124
+ ws.column_dimensions["B"].width = 6
125
+ for column, width in widths.items():
126
+ ws.column_dimensions[get_column_letter(column)].width = width
127
+
128
+ for name, ref in defined:
129
+ definition = DefinedName(name, attr_text=ref)
130
+ try:
131
+ wb.defined_names.add(definition)
132
+ except AttributeError: # 兼容旧版 openpyxl
133
+ wb.defined_names[name] = definition
134
+ if formula_count:
135
+ log(f"[导出] 合计行已写 {formula_count} 个求和公式(在 Excel 改明细后合计自动更新;同步时按公式结果回写 Word)")
136
+ return wb