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.
- package/README.md +152 -148
- package/dsh_plugins/audit-e2w/lib/index.js +9 -1
- package/dsh_plugins/audit-e2w/lib/skill.js +3 -2
- package/excel_word/README.md +45 -37
- package/excel_word/qoder_engine.py +10 -11
- package/excel_word/wesync/__init__.py +1 -1
- package/excel_word/wesync/ai/__init__.py +52 -0
- package/excel_word/wesync/ai/actions.py +369 -0
- package/excel_word/wesync/ai/client.py +340 -0
- package/excel_word/wesync/ai/config.py +291 -0
- package/excel_word/wesync/ai/docs.py +177 -0
- package/excel_word/wesync/ai/prompts.py +288 -0
- package/excel_word/wesync/ai/tasks/__init__.py +26 -0
- package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
- package/excel_word/wesync/ai/tasks/combined.py +123 -0
- package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
- package/excel_word/wesync/ai/tasks/headings.py +119 -0
- package/excel_word/wesync/ai/tasks/help_task.py +69 -0
- package/excel_word/wesync/ai/tasks/roles.py +128 -0
- package/excel_word/wesync/align.py +1 -0
- package/excel_word/wesync/api.py +544 -92
- package/excel_word/wesync/backup_history.py +44 -9
- package/excel_word/wesync/cli.py +19 -1
- package/excel_word/wesync/commands/blank_cmd.py +59 -30
- package/excel_word/wesync/commands/bookmark_cmd.py +41 -10
- package/excel_word/wesync/commands/clear_cmd.py +5 -3
- package/excel_word/wesync/commands/export_cmd.py +270 -220
- package/excel_word/wesync/commands/incremental_cmd.py +157 -0
- package/excel_word/wesync/commands/marks_cmd.py +24 -16
- package/excel_word/wesync/commands/placeholders_cmd.py +12 -7
- package/excel_word/wesync/commands/writeback_cmd.py +72 -116
- package/excel_word/wesync/config.py +3 -2
- package/excel_word/wesync/console.py +9 -2
- package/excel_word/wesync/docx_bookmarks.py +12 -5
- package/excel_word/wesync/docx_columns.py +1 -1
- package/excel_word/wesync/docx_marks.py +183 -75
- package/excel_word/wesync/docx_placeholders.py +65 -26
- package/excel_word/wesync/excel_blocks.py +144 -185
- package/excel_word/wesync/excel_export.py +15 -8
- package/excel_word/wesync/excel_marks.py +265 -193
- package/excel_word/wesync/fsops.py +11 -6
- package/excel_word/wesync/gui/__init__.py +21 -2
- package/excel_word/wesync/gui/app.py +243 -29
- package/excel_word/wesync/gui/manual.py +5 -3
- package/excel_word/wesync/gui/pages/__init__.py +53 -4
- package/excel_word/wesync/gui/pages/_page.py +129 -7
- package/excel_word/wesync/gui/pages/ai_page.py +854 -0
- package/excel_word/wesync/gui/pages/batch_page.py +64 -31
- package/excel_word/wesync/gui/pages/blank_page.py +529 -464
- package/excel_word/wesync/gui/pages/bookmark_page.py +97 -37
- package/excel_word/wesync/gui/pages/export_page.py +140 -87
- package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
- package/excel_word/wesync/gui/pages/format_page.py +551 -429
- package/excel_word/wesync/gui/pages/help_page.py +73 -7
- package/excel_word/wesync/gui/pages/history_page.py +167 -144
- package/excel_word/wesync/gui/pages/marks_page.py +210 -177
- package/excel_word/wesync/gui/pages/settings_page.py +450 -0
- package/excel_word/wesync/gui/pages/writeback_page.py +167 -146
- package/excel_word/wesync/gui/runner.py +29 -13
- package/excel_word/wesync/gui/store.py +23 -7
- package/excel_word/wesync/gui/theme.py +220 -49
- package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
- package/excel_word/wesync/gui/widgets/cards.py +124 -5
- package/excel_word/wesync/gui/widgets/chips.py +565 -0
- package/excel_word/wesync/gui/widgets/filebar.py +1 -1
- package/excel_word/wesync/gui/widgets/logpane.py +24 -8
- package/excel_word/wesync/gui/widgets/nav.py +267 -12
- package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
- package/excel_word/wesync/report_format.py +9 -1
- package/excel_word/wesync/settings.py +35 -0
- package/excel_word/wesync/sort_rules.py +75 -26
- package/excel_word/wesync/valuefmt.py +40 -17
- package/package.json +53 -51
- package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
- package/qoder_plugins/audit-toolbox/README.md +159 -156
- package/qoder_plugins/audit-toolbox/catalog.mjs +13 -13
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
"""Excel 解析层:识别表块与锚点元数据、刷新书签名/链接/列数、刷新 EX_ 定义名称。"""
|
|
2
2
|
|
|
3
|
+
import os
|
|
3
4
|
import re
|
|
4
5
|
from pathlib import Path
|
|
5
6
|
from openpyxl.styles import Alignment, Font
|
|
6
7
|
from openpyxl.utils import get_column_letter
|
|
7
8
|
from openpyxl.workbook.defined_name import DefinedName
|
|
8
9
|
from openpyxl.worksheet.hyperlink import Hyperlink
|
|
9
|
-
from .config import CODE_RE, DELETED_BOOKMARK, FILL_ANCHOR,
|
|
10
|
+
from .config import CODE_RE, DELETED_BOOKMARK, FILL_ANCHOR, FONT_NAME, FONT_SIZE, MARK_DELETED, MARK_HEADER, MARK_NO, MARK_VALUES, MARK_YES, META_SCAN_COLUMNS, NEW_BOOKMARK, SHEET_NAME, SHEET_NEW_TABLES
|
|
10
11
|
from .console import log, warn
|
|
11
|
-
from .fsops import
|
|
12
|
+
from .fsops import load_workbook_for_save
|
|
12
13
|
|
|
13
14
|
|
|
14
15
|
def _cell_str(ws, row: int, col: int) -> str:
|
|
@@ -31,9 +32,7 @@ def row_grid_has_content(ws, row: int, max_col: int, ranges, start_col: int = 2)
|
|
|
31
32
|
cell = ws.cell(row, col)
|
|
32
33
|
if cell.value is not None and str(cell.value).strip() != "":
|
|
33
34
|
return True
|
|
34
|
-
|
|
35
|
-
return True
|
|
36
|
-
return False
|
|
35
|
+
return any(r1 <= row <= r2 and start_col <= c1 <= max_col for (r1, c1, r2, c2) in ranges)
|
|
37
36
|
|
|
38
37
|
|
|
39
38
|
def anchor_metadata(ws, row: int, max_col: int) -> dict:
|
|
@@ -192,8 +191,9 @@ def refresh_defined_names(wb, blocks: dict[str, dict]) -> list[str]:
|
|
|
192
191
|
"""把 EX_Tnn 重新指向各表数据区首行(用户增删行后仍能准确定位)。"""
|
|
193
192
|
changed = []
|
|
194
193
|
for code, block in blocks.items():
|
|
194
|
+
sheet = block.get("sheet_name") or SHEET_NAME
|
|
195
195
|
letter = get_column_letter(block.get("col0", 2))
|
|
196
|
-
ref = f"'{
|
|
196
|
+
ref = f"'{sheet}'!${letter}${block['anchor_row'] + 1}"
|
|
197
197
|
name = f"EX_{code}"
|
|
198
198
|
existing = wb.defined_names.get(name) if hasattr(wb.defined_names, "get") else None
|
|
199
199
|
if existing is not None and existing.attr_text == ref:
|
|
@@ -216,10 +216,16 @@ def read_recorded_bookmarks(xlsx_path: Path) -> dict[str, str]:
|
|
|
216
216
|
except Exception as exc: # 文件被占用或损坏时不阻断主流程
|
|
217
217
|
warn(f"读取现有工作簿失败({exc}),本次不沿用旧书签名")
|
|
218
218
|
return {}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
219
|
+
result = {}
|
|
220
|
+
for sheet_name in (SHEET_NAME, SHEET_NEW_TABLES):
|
|
221
|
+
if sheet_name not in wb.sheetnames:
|
|
222
|
+
continue
|
|
223
|
+
_, blocks = parse_blocks(wb[sheet_name])
|
|
224
|
+
result.update({code: block.get("bookmark", "") for code, block in blocks.items() if block.get("bookmark")})
|
|
225
|
+
wb.close()
|
|
226
|
+
if getattr(wb, "vba_archive", None):
|
|
227
|
+
wb.vba_archive.close()
|
|
228
|
+
return result
|
|
223
229
|
|
|
224
230
|
|
|
225
231
|
def block_merges(ws, block: dict) -> list[tuple[int, int, int, int]]:
|
|
@@ -239,151 +245,6 @@ def block_merges(ws, block: dict) -> list[tuple[int, int, int, int]]:
|
|
|
239
245
|
return result
|
|
240
246
|
|
|
241
247
|
|
|
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
248
|
def rejudge_marks(ws, blocks: dict) -> dict:
|
|
388
249
|
"""按工作簿当前内容重新判定 B 列标记(表头/✓/✕),只改标记不改数据。
|
|
389
250
|
|
|
@@ -431,6 +292,7 @@ def carry_over_deleted_blocks(wb_new, ws_old, blocks_old: dict) -> list[str]:
|
|
|
431
292
|
"""
|
|
432
293
|
from copy import copy
|
|
433
294
|
from openpyxl.utils import get_column_letter
|
|
295
|
+
from .sort_rules import _remap_formula
|
|
434
296
|
|
|
435
297
|
deleted = [b for b in blocks_old.values() if b.get("bookmark") == DELETED_BOOKMARK]
|
|
436
298
|
if not deleted:
|
|
@@ -441,6 +303,7 @@ def carry_over_deleted_blocks(wb_new, ws_old, blocks_old: dict) -> list[str]:
|
|
|
441
303
|
carried: list[str] = []
|
|
442
304
|
new_blocks: dict[str, dict] = {}
|
|
443
305
|
for block in deleted:
|
|
306
|
+
ws_old = block.get("_ws") or ws_old
|
|
444
307
|
code = f"T{next_num:02d}"
|
|
445
308
|
next_num += 1
|
|
446
309
|
old_anchor = block["anchor_row"]
|
|
@@ -461,8 +324,8 @@ def carry_over_deleted_blocks(wb_new, ws_old, blocks_old: dict) -> list[str]:
|
|
|
461
324
|
link.value = None
|
|
462
325
|
link.hyperlink = None
|
|
463
326
|
grid_rows = []
|
|
464
|
-
for i, old_row in enumerate(block["grid_rows"])
|
|
465
|
-
|
|
327
|
+
rowmap = {old_row: anchor + 1 + i for i, old_row in enumerate(block["grid_rows"])}
|
|
328
|
+
for old_row, new_row in rowmap.items():
|
|
466
329
|
grid_rows.append(new_row)
|
|
467
330
|
old = ws_old.cell(old_row, 1)
|
|
468
331
|
new = ws.cell(new_row, 1)
|
|
@@ -478,7 +341,7 @@ def carry_over_deleted_blocks(wb_new, ws_old, blocks_old: dict) -> list[str]:
|
|
|
478
341
|
for c in range(block["ncols"]):
|
|
479
342
|
old = ws_old.cell(old_row, old_col0 + c)
|
|
480
343
|
new = ws.cell(new_row, 3 + c)
|
|
481
|
-
new.value = old.value
|
|
344
|
+
new.value = _remap_formula(old.value, rowmap, ws_old.title) if isinstance(old.value, str) and old.value.startswith("=") else old.value
|
|
482
345
|
if old.has_style:
|
|
483
346
|
new._style = copy(old._style)
|
|
484
347
|
for (r, c, rs, cs) in block_merges(ws_old, block):
|
|
@@ -500,44 +363,140 @@ def carry_over_deleted_blocks(wb_new, ws_old, blocks_old: dict) -> list[str]:
|
|
|
500
363
|
return carried
|
|
501
364
|
|
|
502
365
|
|
|
366
|
+
def repair_workbook_links(xlsx_path: Path, docx_path: Path, *, dry_run: bool = False, backup: bool = True) -> int:
|
|
367
|
+
"""把工作簿里表格与标注的 Word 定位链接改为当前文件的相对路径。"""
|
|
368
|
+
from .excel_marks import SHEET_MARKS
|
|
369
|
+
|
|
370
|
+
wb = load_workbook_for_save(xlsx_path)
|
|
371
|
+
try:
|
|
372
|
+
try:
|
|
373
|
+
target = Path(os.path.relpath(docx_path, xlsx_path.parent)).as_posix()
|
|
374
|
+
except ValueError:
|
|
375
|
+
target = docx_path.as_posix()
|
|
376
|
+
changed = 0
|
|
377
|
+
|
|
378
|
+
def link_state(cell):
|
|
379
|
+
link = cell.hyperlink
|
|
380
|
+
return (link.target if link else None, link.location if link else None)
|
|
381
|
+
|
|
382
|
+
def update_link(cell, bookmark: str, display: str, label: str) -> bool:
|
|
383
|
+
nonlocal changed
|
|
384
|
+
before = (cell.value, link_state(cell))
|
|
385
|
+
cell.value = display
|
|
386
|
+
cell.hyperlink = Hyperlink(
|
|
387
|
+
ref=cell.coordinate, target=target, location=bookmark, display=display
|
|
388
|
+
)
|
|
389
|
+
if before == (cell.value, link_state(cell)):
|
|
390
|
+
return False
|
|
391
|
+
changed += 1
|
|
392
|
+
log(f"[定位] {label} → {target}(书签 {bookmark})")
|
|
393
|
+
return True
|
|
394
|
+
|
|
395
|
+
for sheet_name in (SHEET_NAME, SHEET_NEW_TABLES):
|
|
396
|
+
if sheet_name not in wb.sheetnames:
|
|
397
|
+
continue
|
|
398
|
+
ws = wb[sheet_name]
|
|
399
|
+
_, blocks = parse_blocks(ws)
|
|
400
|
+
for code, block in blocks.items():
|
|
401
|
+
bookmark = block.get("bookmark", "")
|
|
402
|
+
if not bookmark or bookmark in (NEW_BOOKMARK, DELETED_BOOKMARK):
|
|
403
|
+
continue
|
|
404
|
+
row = block["anchor_row"]
|
|
405
|
+
col0 = block.get("col0", 2)
|
|
406
|
+
col = block.get("meta", {}).get("link_col") or col0 + 2
|
|
407
|
+
update_link(ws.cell(row, col), bookmark, "→定位Word表", f"{sheet_name} {code}")
|
|
408
|
+
|
|
409
|
+
if SHEET_MARKS in wb.sheetnames:
|
|
410
|
+
ws = wb[SHEET_MARKS]
|
|
411
|
+
headers = {str(ws.cell(1, col).value or "").strip(): col for col in range(1, ws.max_column + 1)}
|
|
412
|
+
bookmark_col = headers.get("书签")
|
|
413
|
+
link_col = headers.get("→定位Word")
|
|
414
|
+
if bookmark_col and link_col:
|
|
415
|
+
for row in range(2, (ws.max_row or 1) + 1):
|
|
416
|
+
bookmark = str(ws.cell(row, bookmark_col).value or "").strip()
|
|
417
|
+
cell = ws.cell(row, link_col)
|
|
418
|
+
if not bookmark or (cell.value != "→定位Word" and cell.hyperlink is None):
|
|
419
|
+
continue
|
|
420
|
+
update_link(cell, bookmark, "→定位Word", f"{SHEET_MARKS} 第 {row} 行")
|
|
421
|
+
|
|
422
|
+
if not changed:
|
|
423
|
+
log("[定位] Excel 中的表格与标注链接已是目标状态,无需改动")
|
|
424
|
+
return 0
|
|
425
|
+
if dry_run:
|
|
426
|
+
log(f"预演模式:将修复 {changed} 个 Word 定位链接,未写入文件。")
|
|
427
|
+
return changed
|
|
428
|
+
from .fsops import save_docx_xlsx_transaction
|
|
429
|
+
|
|
430
|
+
saved_backup = save_docx_xlsx_transaction(
|
|
431
|
+
xlsx_path=xlsx_path, wb=wb, backup=backup,
|
|
432
|
+
).get(xlsx_path)
|
|
433
|
+
log(f"[定位] 已修复 {changed} 个链接并保存 {xlsx_path.name}" + (f"(原文件已备份:{saved_backup.name})" if saved_backup else ""))
|
|
434
|
+
return changed
|
|
435
|
+
finally:
|
|
436
|
+
wb.close()
|
|
437
|
+
if getattr(wb, "vba_archive", None):
|
|
438
|
+
wb.vba_archive.close()
|
|
439
|
+
|
|
440
|
+
|
|
503
441
|
def refresh_workbook_metadata(
|
|
504
442
|
xlsx_path: Path,
|
|
505
443
|
docx_name: str,
|
|
506
444
|
infos_by_code: dict[str, dict],
|
|
507
445
|
with_links: bool = True,
|
|
446
|
+
backup: bool = True,
|
|
447
|
+
docx_path: Path | None = None,
|
|
508
448
|
) -> int:
|
|
509
449
|
"""刷新工作簿里的书签名、跳转链接与列数(不动任何数据单元格)。"""
|
|
510
450
|
wb = load_workbook_for_save(xlsx_path)
|
|
511
|
-
|
|
451
|
+
sheets = [(name, wb[name]) for name in (SHEET_NAME, SHEET_NEW_TABLES) if name in wb.sheetnames]
|
|
452
|
+
if not sheets:
|
|
453
|
+
wb.close()
|
|
512
454
|
return 0
|
|
513
|
-
ws = wb[SHEET_NAME]
|
|
514
|
-
_, blocks = parse_blocks(ws)
|
|
515
455
|
changed = 0
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
456
|
+
all_blocks: dict[str, dict] = {}
|
|
457
|
+
for sheet_name, ws in sheets:
|
|
458
|
+
_, blocks = parse_blocks(ws)
|
|
459
|
+
for block in blocks.values():
|
|
460
|
+
block["sheet_name"] = sheet_name
|
|
461
|
+
all_blocks.update(blocks)
|
|
462
|
+
for code, block in blocks.items():
|
|
463
|
+
info = infos_by_code.get(code)
|
|
464
|
+
if info is None:
|
|
465
|
+
continue
|
|
466
|
+
row = block["anchor_row"]
|
|
467
|
+
col0 = block.get("col0", 2)
|
|
468
|
+
link_cell = ws.cell(row, col0 + 2)
|
|
469
|
+
before = [
|
|
470
|
+
ws.cell(row, col).value for col in range(1, col0 + 4)
|
|
471
|
+
] + [
|
|
472
|
+
(link_cell.hyperlink.target if link_cell.hyperlink else None,
|
|
473
|
+
link_cell.hyperlink.location if link_cell.hyperlink else None)
|
|
474
|
+
]
|
|
475
|
+
target = docx_name
|
|
476
|
+
if docx_path is not None:
|
|
477
|
+
try:
|
|
478
|
+
target = Path(os.path.relpath(docx_path, xlsx_path.parent)).as_posix()
|
|
479
|
+
except ValueError:
|
|
480
|
+
target = docx_path.as_posix()
|
|
481
|
+
refresh_anchor_metadata(ws, block, info, target, with_link=with_links, ncols=block["ncols"])
|
|
482
|
+
link_cell = ws.cell(row, col0 + 2)
|
|
483
|
+
after = [
|
|
484
|
+
ws.cell(row, col).value for col in range(1, col0 + 4)
|
|
485
|
+
] + [
|
|
486
|
+
(link_cell.hyperlink.target if link_cell.hyperlink else None,
|
|
487
|
+
link_cell.hyperlink.location if link_cell.hyperlink else None)
|
|
488
|
+
]
|
|
489
|
+
if before != after:
|
|
490
|
+
changed += 1
|
|
491
|
+
log(f"[定位] {code}:书签/链接已刷新为 {info['bookmark']}")
|
|
492
|
+
names = refresh_defined_names(wb, all_blocks)
|
|
537
493
|
if changed or names:
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
494
|
+
from .fsops import save_docx_xlsx_transaction
|
|
495
|
+
|
|
496
|
+
saved_backup = save_docx_xlsx_transaction(
|
|
497
|
+
xlsx_path=xlsx_path, wb=wb, backup=backup,
|
|
498
|
+
).get(xlsx_path)
|
|
499
|
+
log(f"[定位] 已保存 {xlsx_path.name}" + (f"(原文件已备份:{saved_backup.name})" if saved_backup else ""))
|
|
541
500
|
else:
|
|
542
501
|
log("[定位] Excel 中的书签名与链接已是目标状态,无需改动")
|
|
543
502
|
return changed + len(names)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Excel 导出层:把 Word 表格生成为单工作表堆叠结构(样式、合并、跳转链接、定义名称)。"""
|
|
2
2
|
|
|
3
3
|
from openpyxl import Workbook
|
|
4
|
-
from openpyxl.styles import Alignment, Border, Font,
|
|
4
|
+
from openpyxl.styles import Alignment, Border, Font, Side
|
|
5
5
|
from openpyxl.utils import get_column_letter
|
|
6
6
|
from openpyxl.workbook.defined_name import DefinedName
|
|
7
7
|
from openpyxl.worksheet.hyperlink import Hyperlink
|
|
@@ -20,15 +20,20 @@ def make_border(sides: dict) -> Border:
|
|
|
20
20
|
return Border(left=side("left"), right=side("right"), top=side("top"), bottom=side("bottom"))
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
def export_workbook(infos: list[dict], docx_name: str, with_links: bool = True, totals_formula: bool = True
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
def export_workbook(infos: list[dict], docx_name: str, with_links: bool = True, totals_formula: bool = True,
|
|
24
|
+
*, wb=None, sheet_name: str = SHEET_NAME) -> Workbook:
|
|
25
|
+
wb = wb or Workbook()
|
|
26
|
+
if sheet_name in wb.sheetnames:
|
|
27
|
+
ws = wb[sheet_name]
|
|
28
|
+
else:
|
|
29
|
+
ws = wb.active if len(wb.worksheets) == 1 and wb.active.max_row == 1 and wb.active["A1"].value is None else wb.create_sheet()
|
|
30
|
+
ws.title = sheet_name
|
|
31
|
+
if ws.title == sheet_name and not ws.column_dimensions["A"].width:
|
|
32
|
+
ws.column_dimensions["A"].width = 7
|
|
28
33
|
ws.freeze_panes = "A1"
|
|
29
34
|
|
|
30
35
|
widths: dict[int, float] = {}
|
|
31
|
-
row = 1
|
|
36
|
+
row = (ws.max_row or 0) + 2 if ws.max_row and ws.max_row > 1 else 1
|
|
32
37
|
defined: list[tuple[str, str]] = []
|
|
33
38
|
formula_count = 0
|
|
34
39
|
|
|
@@ -90,6 +95,8 @@ def export_workbook(infos: list[dict], docx_name: str, with_links: bool = True,
|
|
|
90
95
|
cell.value = formula
|
|
91
96
|
elif value is not None:
|
|
92
97
|
cell.value = value
|
|
98
|
+
if isinstance(value, str):
|
|
99
|
+
cell.data_type = "s" # Word 来源的 = 文本不是公式
|
|
93
100
|
cell.number_format = number_format or ("@" if isinstance(value, str) else "General")
|
|
94
101
|
cell.alignment = Alignment(
|
|
95
102
|
horizontal=horizontal, vertical=vertical, wrap_text=True if isinstance(value, str) and "\n" in value else False
|
|
@@ -118,7 +125,7 @@ def export_workbook(infos: list[dict], docx_name: str, with_links: bool = True,
|
|
|
118
125
|
anchor_cell = ws.cell(grid_start + r, 3 + c)
|
|
119
126
|
anchor_cell.border = make_border({"top": top, "left": left, "bottom": bottom, "right": right})
|
|
120
127
|
|
|
121
|
-
defined.append((f"EX_{code}", f"'{
|
|
128
|
+
defined.append((f"EX_{code}", f"'{sheet_name}'!$C${grid_start}"))
|
|
122
129
|
row = grid_start + nrows + 1 # 表间空一行
|
|
123
130
|
|
|
124
131
|
ws.column_dimensions["B"].width = 6
|