audit-e2w 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +152 -3
- package/cordis.patch.yml +3 -0
- package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
- package/dsh_plugins/audit-e2w/lib/index.js +122 -0
- package/dsh_plugins/audit-e2w/lib/skill.js +42 -0
- package/excel_word/README.md +388 -0
- package/excel_word/qoder_engine.py +437 -0
- package/excel_word/requirements.txt +4 -0
- package/excel_word/wesync/__init__.py +19 -0
- package/excel_word/wesync/__main__.py +6 -0
- package/excel_word/wesync/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 +155 -0
- package/excel_word/wesync/api.py +1292 -0
- package/excel_word/wesync/backup_history.py +100 -0
- package/excel_word/wesync/changelog.py +58 -0
- package/excel_word/wesync/cli.py +191 -0
- package/excel_word/wesync/commands/__init__.py +8 -0
- package/excel_word/wesync/commands/blank_cmd.py +279 -0
- package/excel_word/wesync/commands/bookmark_cmd.py +146 -0
- package/excel_word/wesync/commands/clear_cmd.py +50 -0
- package/excel_word/wesync/commands/export_cmd.py +270 -0
- package/excel_word/wesync/commands/incremental_cmd.py +157 -0
- package/excel_word/wesync/commands/marks_cmd.py +160 -0
- package/excel_word/wesync/commands/placeholders_cmd.py +92 -0
- package/excel_word/wesync/commands/writeback_cmd.py +469 -0
- package/excel_word/wesync/config.py +97 -0
- package/excel_word/wesync/console.py +85 -0
- package/excel_word/wesync/docx_blank.py +156 -0
- package/excel_word/wesync/docx_bookmarks.py +294 -0
- package/excel_word/wesync/docx_columns.py +257 -0
- package/excel_word/wesync/docx_edit.py +77 -0
- package/excel_word/wesync/docx_grid.py +212 -0
- package/excel_word/wesync/docx_marks.py +399 -0
- package/excel_word/wesync/docx_meta.py +157 -0
- package/excel_word/wesync/docx_newtable.py +220 -0
- package/excel_word/wesync/docx_placeholders.py +200 -0
- package/excel_word/wesync/docx_rows.py +67 -0
- package/excel_word/wesync/errors.py +5 -0
- package/excel_word/wesync/excel_blocks.py +502 -0
- package/excel_word/wesync/excel_export.py +143 -0
- package/excel_word/wesync/excel_marks.py +265 -0
- package/excel_word/wesync/excel_totals.py +53 -0
- package/excel_word/wesync/fsops.py +219 -0
- package/excel_word/wesync/gui/__init__.py +53 -0
- package/excel_word/wesync/gui/__main__.py +6 -0
- package/excel_word/wesync/gui/app.py +613 -0
- package/excel_word/wesync/gui/manual.py +70 -0
- package/excel_word/wesync/gui/pages/__init__.py +80 -0
- package/excel_word/wesync/gui/pages/_page.py +211 -0
- package/excel_word/wesync/gui/pages/ai_page.py +854 -0
- package/excel_word/wesync/gui/pages/batch_page.py +456 -0
- package/excel_word/wesync/gui/pages/blank_page.py +530 -0
- package/excel_word/wesync/gui/pages/bookmark_page.py +97 -0
- package/excel_word/wesync/gui/pages/export_page.py +141 -0
- package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
- package/excel_word/wesync/gui/pages/format_page.py +551 -0
- package/excel_word/wesync/gui/pages/help_page.py +158 -0
- package/excel_word/wesync/gui/pages/history_page.py +168 -0
- package/excel_word/wesync/gui/pages/marks_page.py +211 -0
- package/excel_word/wesync/gui/pages/settings_page.py +450 -0
- package/excel_word/wesync/gui/pages/writeback_page.py +473 -0
- package/excel_word/wesync/gui/resources.py +22 -0
- package/excel_word/wesync/gui/runner.py +90 -0
- package/excel_word/wesync/gui/store.py +50 -0
- package/excel_word/wesync/gui/theme.py +271 -0
- package/excel_word/wesync/gui/widgets/__init__.py +8 -0
- package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
- package/excel_word/wesync/gui/widgets/cards.py +139 -0
- package/excel_word/wesync/gui/widgets/chips.py +565 -0
- package/excel_word/wesync/gui/widgets/filebar.py +58 -0
- package/excel_word/wesync/gui/widgets/logpane.py +126 -0
- package/excel_word/wesync/gui/widgets/nav.py +294 -0
- package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
- package/excel_word/wesync/report_format.py +1585 -0
- package/excel_word/wesync/settings.py +35 -0
- package/excel_word/wesync/sort_rules.py +293 -0
- package/excel_word/wesync/valuefmt.py +485 -0
- package/package.json +53 -6
- 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 -0
- package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
"""Excel 解析层:识别表块与锚点元数据、刷新书签名/链接/列数、刷新 EX_ 定义名称。"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from openpyxl.styles import Alignment, Font
|
|
7
|
+
from openpyxl.utils import get_column_letter
|
|
8
|
+
from openpyxl.workbook.defined_name import DefinedName
|
|
9
|
+
from openpyxl.worksheet.hyperlink import Hyperlink
|
|
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
|
|
11
|
+
from .console import log, warn
|
|
12
|
+
from .fsops import load_workbook_for_save
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _cell_str(ws, row: int, col: int) -> str:
|
|
16
|
+
value = ws.cell(row, col).value
|
|
17
|
+
if value is None:
|
|
18
|
+
return ""
|
|
19
|
+
return str(value).strip()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _merged_ranges(ws) -> list[tuple[int, int, int, int]]:
|
|
23
|
+
return [(r.min_row, r.min_col, r.max_row, r.max_col) for r in ws.merged_cells.ranges]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _in_merged(ranges, row: int, col: int) -> bool:
|
|
27
|
+
return any(r1 <= row <= r2 and c1 <= col <= c2 for (r1, c1, r2, c2) in ranges)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def row_grid_has_content(ws, row: int, max_col: int, ranges, start_col: int = 2) -> bool:
|
|
31
|
+
for col in range(start_col, max(max_col, start_col) + 1):
|
|
32
|
+
cell = ws.cell(row, col)
|
|
33
|
+
if cell.value is not None and str(cell.value).strip() != "":
|
|
34
|
+
return True
|
|
35
|
+
return any(r1 <= row <= r2 and start_col <= c1 <= max_col for (r1, c1, r2, c2) in ranges)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def anchor_metadata(ws, row: int, max_col: int) -> dict:
|
|
39
|
+
"""按内容特征定位锚点行的元数据,兼容插入列后整体右移的情况。"""
|
|
40
|
+
meta: dict = {"name": "", "bookmark": "", "ncols": None, "link_col": None, "after": "", "restore_after": "", "caption": "", "sort": "", "cols": {}}
|
|
41
|
+
for col in range(1, min(max_col, META_SCAN_COLUMNS) + 1):
|
|
42
|
+
cell = ws.cell(row, col)
|
|
43
|
+
text = "" if cell.value is None else str(cell.value).strip()
|
|
44
|
+
if col > 1 and cell.hyperlink is not None and meta["link_col"] is None:
|
|
45
|
+
meta["link_col"] = col
|
|
46
|
+
meta["cols"]["link"] = col
|
|
47
|
+
if text.startswith("书签:"):
|
|
48
|
+
meta["cols"]["bookmark"] = col
|
|
49
|
+
meta["bookmark"] = text.split(":", 1)[1].split("(", 1)[0].strip()
|
|
50
|
+
elif col >= 2 and text in (NEW_BOOKMARK, "新表"):
|
|
51
|
+
meta["cols"]["bookmark"] = col
|
|
52
|
+
meta["bookmark"] = NEW_BOOKMARK
|
|
53
|
+
elif text.startswith("列数:"):
|
|
54
|
+
meta["cols"]["ncols"] = col
|
|
55
|
+
match = re.search(r"(\d+)", text)
|
|
56
|
+
if match:
|
|
57
|
+
meta["ncols"] = int(match.group(1))
|
|
58
|
+
elif col >= 2 and text.startswith("位置:"):
|
|
59
|
+
meta["cols"]["pos"] = col
|
|
60
|
+
value = text.split(":", 1)[1].strip()
|
|
61
|
+
match = re.match(r"T\d{2,}", value)
|
|
62
|
+
meta["after"] = match.group(0) if match else "末尾"
|
|
63
|
+
elif col >= 2 and text.startswith("原位置:"):
|
|
64
|
+
meta["cols"]["restore_pos"] = col
|
|
65
|
+
value = text.split(":", 1)[1].strip()
|
|
66
|
+
meta["restore_after"] = value[:-2] if value.endswith("之后") else "末尾"
|
|
67
|
+
elif col >= 2 and text.startswith("原标题:"):
|
|
68
|
+
meta["cols"]["caption"] = col
|
|
69
|
+
meta["caption"] = text.split(":", 1)[1].strip()
|
|
70
|
+
elif col >= 2 and text.startswith("排序:"):
|
|
71
|
+
meta["cols"]["sort"] = col
|
|
72
|
+
meta["sort"] = text
|
|
73
|
+
elif col >= 2 and not meta["name"] and ("【表" in text or text.startswith("【新表】")):
|
|
74
|
+
meta["cols"]["name"] = col
|
|
75
|
+
meta["name"] = text
|
|
76
|
+
return meta
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def parse_blocks(ws) -> tuple[list[str], dict[str, dict]]:
|
|
80
|
+
"""解析表块。
|
|
81
|
+
|
|
82
|
+
块归属规则:A 列为表编号的行、以及 A 列为空但网格区有内容的行(例如用户在块中间
|
|
83
|
+
插入行后直接填数据)都计入当前表块;整行空白视为分隔行,不计入行数。
|
|
84
|
+
"""
|
|
85
|
+
order: list[str] = []
|
|
86
|
+
blocks: dict[str, dict] = {}
|
|
87
|
+
max_row = ws.max_row or 0
|
|
88
|
+
max_col = ws.max_column or 0
|
|
89
|
+
ranges = _merged_ranges(ws)
|
|
90
|
+
current: dict | None = None
|
|
91
|
+
|
|
92
|
+
for row in range(1, max_row + 1):
|
|
93
|
+
code = _cell_str(ws, row, 1)
|
|
94
|
+
if CODE_RE.match(code):
|
|
95
|
+
if current is not None and current["code"] == code:
|
|
96
|
+
if current["col0"] == 3 and _cell_str(ws, row, 2) == MARK_DELETED:
|
|
97
|
+
continue # 「已删」墓碑行不计入网格
|
|
98
|
+
current["grid_rows"].append(row) # 块内数据行同样带表编号
|
|
99
|
+
continue
|
|
100
|
+
meta = anchor_metadata(ws, row, max_col)
|
|
101
|
+
current = {
|
|
102
|
+
"code": code,
|
|
103
|
+
"anchor_row": row,
|
|
104
|
+
"grid_rows": [],
|
|
105
|
+
"meta": meta,
|
|
106
|
+
"col0": 3 if meta["cols"].get("name") == 3 else 2,
|
|
107
|
+
}
|
|
108
|
+
blocks[code] = current
|
|
109
|
+
order.append(code)
|
|
110
|
+
continue
|
|
111
|
+
if current is None or code != "":
|
|
112
|
+
continue
|
|
113
|
+
if current["col0"] == 3 and _cell_str(ws, row, 2) == MARK_DELETED:
|
|
114
|
+
continue
|
|
115
|
+
if row_grid_has_content(ws, row, max_col, ranges, start_col=current["col0"]):
|
|
116
|
+
current["grid_rows"].append(row)
|
|
117
|
+
|
|
118
|
+
for block in blocks.values():
|
|
119
|
+
head_mark = _cell_str(ws, block["grid_rows"][0], 2) if block["grid_rows"] else ""
|
|
120
|
+
second_mark = _cell_str(ws, block["grid_rows"][1], 2) if len(block["grid_rows"]) > 1 else ""
|
|
121
|
+
if block["col0"] == 2 and head_mark in MARK_VALUES and second_mark in (MARK_YES, MARK_NO, MARK_DELETED):
|
|
122
|
+
block["col0"] = 3
|
|
123
|
+
col0 = block["col0"]
|
|
124
|
+
inferred = 0
|
|
125
|
+
for grid_row in block["grid_rows"]:
|
|
126
|
+
for col in range(max(max_col, 2), 1, -1):
|
|
127
|
+
cell = ws.cell(grid_row, col)
|
|
128
|
+
filled = cell.value is not None and str(cell.value).strip() != ""
|
|
129
|
+
# 空格子但带格式,说明它属于导出的网格(例如整列为空的表格列)
|
|
130
|
+
if filled or cell.has_style or _in_merged(ranges, grid_row, col):
|
|
131
|
+
inferred = max(inferred, col - col0 + 1)
|
|
132
|
+
break
|
|
133
|
+
block["ncols"] = inferred
|
|
134
|
+
block["bookmark"] = block["meta"].get("bookmark", "")
|
|
135
|
+
block["is_new"] = block["bookmark"] == NEW_BOOKMARK
|
|
136
|
+
if block["is_new"]:
|
|
137
|
+
# 新表块要按"连续网格"取行:空但有样式的行(模板/Excel 插入行)也算表格行
|
|
138
|
+
declared = block["meta"].get("ncols")
|
|
139
|
+
ncols = declared or inferred or 1
|
|
140
|
+
rows = []
|
|
141
|
+
row = block["anchor_row"] + 1
|
|
142
|
+
while row <= max_row:
|
|
143
|
+
code_text = _cell_str(ws, row, 1)
|
|
144
|
+
if code_text and code_text != block["code"]:
|
|
145
|
+
break
|
|
146
|
+
if _cell_str(ws, row, 2) == MARK_DELETED:
|
|
147
|
+
break
|
|
148
|
+
has = row_grid_has_content(ws, row, max_col, ranges, start_col=col0) or any(
|
|
149
|
+
ws.cell(row, col).has_style for col in range(col0, col0 + ncols)
|
|
150
|
+
)
|
|
151
|
+
if not has:
|
|
152
|
+
break
|
|
153
|
+
rows.append(row)
|
|
154
|
+
row += 1
|
|
155
|
+
block["grid_rows"] = rows
|
|
156
|
+
block["ncols"] = declared or max(inferred, 1)
|
|
157
|
+
return order, blocks
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def refresh_anchor_metadata(ws, block: dict, info: dict, docx_name: str, with_link: bool = True, ncols: int | None = None) -> None:
|
|
161
|
+
"""把锚点行元数据写回规范位置(col0 名称 / +1 书签 / +2 链接 / +3 列数),并清理错位残留。"""
|
|
162
|
+
row = block["anchor_row"]
|
|
163
|
+
col0 = block.get("col0", 2)
|
|
164
|
+
for col in range(col0, META_SCAN_COLUMNS + 1):
|
|
165
|
+
if col in (col0, col0 + 1, col0 + 2, col0 + 3):
|
|
166
|
+
continue
|
|
167
|
+
cell = ws.cell(row, col)
|
|
168
|
+
text = "" if cell.value is None else str(cell.value).strip()
|
|
169
|
+
if text.startswith(("书签:", "列数:", "位置:", "原位置:", "原标题:")) or text == "→定位Word表":
|
|
170
|
+
cell.value = None
|
|
171
|
+
cell.hyperlink = None
|
|
172
|
+
|
|
173
|
+
ws.cell(row, col0, f"【表{info['index'] + 1}】{info['name']} · 章节:{info['section']}")
|
|
174
|
+
ws.cell(row, col0 + 1, f"书签:{info['bookmark']}")
|
|
175
|
+
link_cell = ws.cell(row, col0 + 2, "→定位Word表")
|
|
176
|
+
if with_link:
|
|
177
|
+
link_cell.hyperlink = Hyperlink(
|
|
178
|
+
ref=link_cell.coordinate, target=docx_name, location=info["bookmark"], display="→定位Word表"
|
|
179
|
+
)
|
|
180
|
+
else:
|
|
181
|
+
link_cell.hyperlink = None
|
|
182
|
+
ws.cell(row, col0 + 3, f"列数:{ncols if ncols is not None else info['ncols']}")
|
|
183
|
+
for col in range(1, col0 + 4):
|
|
184
|
+
cell = ws.cell(row, col)
|
|
185
|
+
cell.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True, color="1F4E79")
|
|
186
|
+
cell.fill = FILL_ANCHOR
|
|
187
|
+
cell.alignment = Alignment(horizontal="left" if col > 1 else "center", vertical="center")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def refresh_defined_names(wb, blocks: dict[str, dict]) -> list[str]:
|
|
191
|
+
"""把 EX_Tnn 重新指向各表数据区首行(用户增删行后仍能准确定位)。"""
|
|
192
|
+
changed = []
|
|
193
|
+
for code, block in blocks.items():
|
|
194
|
+
sheet = block.get("sheet_name") or SHEET_NAME
|
|
195
|
+
letter = get_column_letter(block.get("col0", 2))
|
|
196
|
+
ref = f"'{sheet}'!${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
|
+
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
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def block_merges(ws, block: dict) -> list[tuple[int, int, int, int]]:
|
|
232
|
+
"""表块网格内的 Excel 合并区 → (起始行, 起始列, 行跨度, 列跨度),坐标相对块内网格。"""
|
|
233
|
+
rows = block["grid_rows"]
|
|
234
|
+
if not rows:
|
|
235
|
+
return []
|
|
236
|
+
row_index = {r: i for i, r in enumerate(rows)}
|
|
237
|
+
ncols = block["ncols"]
|
|
238
|
+
col0 = block.get("col0", 2)
|
|
239
|
+
result = []
|
|
240
|
+
for (r1, c1, r2, c2) in _merged_ranges(ws):
|
|
241
|
+
if c1 < col0 or c1 > col0 - 1 + ncols or r1 not in row_index or r2 not in row_index:
|
|
242
|
+
continue
|
|
243
|
+
c2 = min(c2, col0 - 1 + ncols)
|
|
244
|
+
result.append((row_index[r1], c1 - col0, row_index[r2] - row_index[r1] + 1, c2 - c1 + 1))
|
|
245
|
+
return result
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def rejudge_marks(ws, blocks: dict) -> dict:
|
|
249
|
+
"""按工作簿当前内容重新判定 B 列标记(表头/✓/✕),只改标记不改数据。
|
|
250
|
+
|
|
251
|
+
仅新布局表块(col0=3)参与:网格首行=表头;其余行除首列外任一列有内容
|
|
252
|
+
(含公式、「—」等占位文字)=✓,否则=✕,口径与导出时一致。
|
|
253
|
+
「已删」行不在 grid_rows 里,天然保持原样。旧布局块记入 old 列表提示重新导出。
|
|
254
|
+
"""
|
|
255
|
+
changed = 0
|
|
256
|
+
rows = 0
|
|
257
|
+
old: list[str] = []
|
|
258
|
+
for code, block in blocks.items():
|
|
259
|
+
if block.get("col0", 2) != 3:
|
|
260
|
+
old.append(code)
|
|
261
|
+
continue
|
|
262
|
+
col0, ncols = block["col0"], block["ncols"]
|
|
263
|
+
for i, row in enumerate(block["grid_rows"]):
|
|
264
|
+
rows += 1
|
|
265
|
+
if i == 0:
|
|
266
|
+
mark, color = MARK_HEADER, "808080"
|
|
267
|
+
else:
|
|
268
|
+
has = False
|
|
269
|
+
for c in range(1, ncols):
|
|
270
|
+
cell = ws.cell(row, col0 + c)
|
|
271
|
+
value = cell.value
|
|
272
|
+
if isinstance(value, str) and value.startswith("="):
|
|
273
|
+
has = True
|
|
274
|
+
break
|
|
275
|
+
if value is not None and str(value).strip():
|
|
276
|
+
has = True
|
|
277
|
+
break
|
|
278
|
+
mark, color = (MARK_YES, "008000") if has else (MARK_NO, "C00000")
|
|
279
|
+
mark_cell = ws.cell(row, 2)
|
|
280
|
+
if mark_cell.value != mark:
|
|
281
|
+
changed += 1
|
|
282
|
+
mark_cell.value = mark
|
|
283
|
+
mark_cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color=color)
|
|
284
|
+
mark_cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
285
|
+
return {"changed": changed, "rows": rows, "old": old}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def carry_over_deleted_blocks(wb_new, ws_old, blocks_old: dict) -> list[str]:
|
|
289
|
+
"""导出重建工作簿时,把「已可逆删除」的表块原样保留到新工作簿末尾。
|
|
290
|
+
|
|
291
|
+
复制值、样式、合并区与锚点记录(原位置/原标题),编号顺延;返回保留的表编号。
|
|
292
|
+
"""
|
|
293
|
+
from copy import copy
|
|
294
|
+
from openpyxl.utils import get_column_letter
|
|
295
|
+
from .sort_rules import _remap_formula
|
|
296
|
+
|
|
297
|
+
deleted = [b for b in blocks_old.values() if b.get("bookmark") == DELETED_BOOKMARK]
|
|
298
|
+
if not deleted:
|
|
299
|
+
return []
|
|
300
|
+
ws = wb_new[SHEET_NAME]
|
|
301
|
+
order, _ = parse_blocks(ws)
|
|
302
|
+
next_num = max([int(code[1:]) for code in order if code[1:].isdigit()] + [0]) + 1
|
|
303
|
+
carried: list[str] = []
|
|
304
|
+
new_blocks: dict[str, dict] = {}
|
|
305
|
+
for block in deleted:
|
|
306
|
+
ws_old = block.get("_ws") or ws_old
|
|
307
|
+
code = f"T{next_num:02d}"
|
|
308
|
+
next_num += 1
|
|
309
|
+
old_anchor = block["anchor_row"]
|
|
310
|
+
old_col0 = block.get("col0", 2)
|
|
311
|
+
anchor = (ws.max_row or 0) + 2
|
|
312
|
+
for col in range(1, META_SCAN_COLUMNS + 1):
|
|
313
|
+
old = ws_old.cell(old_anchor, col)
|
|
314
|
+
if old.value is None and not old.has_style:
|
|
315
|
+
continue
|
|
316
|
+
new_col = 1 if col == 1 else (col if col < old_col0 else col + 3 - old_col0)
|
|
317
|
+
new = ws.cell(anchor, new_col)
|
|
318
|
+
new.value = old.value
|
|
319
|
+
if old.has_style:
|
|
320
|
+
new._style = copy(old._style)
|
|
321
|
+
ws.cell(anchor, 1, code)
|
|
322
|
+
ws.cell(anchor, 4, f"书签:{DELETED_BOOKMARK}")
|
|
323
|
+
link = ws.cell(anchor, 5)
|
|
324
|
+
link.value = None
|
|
325
|
+
link.hyperlink = None
|
|
326
|
+
grid_rows = []
|
|
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():
|
|
329
|
+
grid_rows.append(new_row)
|
|
330
|
+
old = ws_old.cell(old_row, 1)
|
|
331
|
+
new = ws.cell(new_row, 1)
|
|
332
|
+
new.value = code
|
|
333
|
+
if old.has_style:
|
|
334
|
+
new._style = copy(old._style)
|
|
335
|
+
if old_col0 == 3:
|
|
336
|
+
old = ws_old.cell(old_row, 2)
|
|
337
|
+
new = ws.cell(new_row, 2)
|
|
338
|
+
new.value = old.value
|
|
339
|
+
if old.has_style:
|
|
340
|
+
new._style = copy(old._style)
|
|
341
|
+
for c in range(block["ncols"]):
|
|
342
|
+
old = ws_old.cell(old_row, old_col0 + c)
|
|
343
|
+
new = ws.cell(new_row, 3 + c)
|
|
344
|
+
new.value = _remap_formula(old.value, rowmap, ws_old.title) if isinstance(old.value, str) and old.value.startswith("=") else old.value
|
|
345
|
+
if old.has_style:
|
|
346
|
+
new._style = copy(old._style)
|
|
347
|
+
for (r, c, rs, cs) in block_merges(ws_old, block):
|
|
348
|
+
if rs == 1 and cs == 1:
|
|
349
|
+
continue
|
|
350
|
+
ws.merge_cells(
|
|
351
|
+
start_row=anchor + 1 + r, start_column=3 + c,
|
|
352
|
+
end_row=anchor + r + rs, end_column=2 + c + cs,
|
|
353
|
+
)
|
|
354
|
+
for c in range(block["ncols"]):
|
|
355
|
+
old_dim = ws_old.column_dimensions.get(get_column_letter(old_col0 + c))
|
|
356
|
+
if old_dim is not None and old_dim.width:
|
|
357
|
+
letter = get_column_letter(3 + c)
|
|
358
|
+
cur = ws.column_dimensions[letter].width or 0
|
|
359
|
+
ws.column_dimensions[letter].width = max(cur, old_dim.width)
|
|
360
|
+
new_blocks[code] = {"code": code, "anchor_row": anchor, "grid_rows": grid_rows, "ncols": block["ncols"], "col0": 3}
|
|
361
|
+
carried.append(code)
|
|
362
|
+
refresh_defined_names(wb_new, new_blocks)
|
|
363
|
+
return carried
|
|
364
|
+
|
|
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
|
+
|
|
441
|
+
def refresh_workbook_metadata(
|
|
442
|
+
xlsx_path: Path,
|
|
443
|
+
docx_name: str,
|
|
444
|
+
infos_by_code: dict[str, dict],
|
|
445
|
+
with_links: bool = True,
|
|
446
|
+
backup: bool = True,
|
|
447
|
+
docx_path: Path | None = None,
|
|
448
|
+
) -> int:
|
|
449
|
+
"""刷新工作簿里的书签名、跳转链接与列数(不动任何数据单元格)。"""
|
|
450
|
+
wb = load_workbook_for_save(xlsx_path)
|
|
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()
|
|
454
|
+
return 0
|
|
455
|
+
changed = 0
|
|
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)
|
|
493
|
+
if changed or names:
|
|
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 ""))
|
|
500
|
+
else:
|
|
501
|
+
log("[定位] Excel 中的书签名与链接已是目标状态,无需改动")
|
|
502
|
+
return changed + len(names)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Excel 导出层:把 Word 表格生成为单工作表堆叠结构(样式、合并、跳转链接、定义名称)。"""
|
|
2
|
+
|
|
3
|
+
from openpyxl import Workbook
|
|
4
|
+
from openpyxl.styles import Alignment, Border, Font, 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,
|
|
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
|
|
33
|
+
ws.freeze_panes = "A1"
|
|
34
|
+
|
|
35
|
+
widths: dict[int, float] = {}
|
|
36
|
+
row = (ws.max_row or 0) + 2 if ws.max_row and ws.max_row > 1 else 1
|
|
37
|
+
defined: list[tuple[str, str]] = []
|
|
38
|
+
formula_count = 0
|
|
39
|
+
|
|
40
|
+
for info in infos:
|
|
41
|
+
anchor_row = row
|
|
42
|
+
code = info["code"]
|
|
43
|
+
|
|
44
|
+
ws.cell(anchor_row, 1, code)
|
|
45
|
+
ws.cell(anchor_row, 3, f"【表{info['index'] + 1}】{info['name']} · 章节:{info['section']}")
|
|
46
|
+
meta_text = f"书签:{info['bookmark']}"
|
|
47
|
+
if info.get("old_bookmark"):
|
|
48
|
+
meta_text += f"(原审计软件书签:{info['old_bookmark']})"
|
|
49
|
+
ws.cell(anchor_row, 4, meta_text)
|
|
50
|
+
link_cell = ws.cell(anchor_row, 5, "→定位Word表")
|
|
51
|
+
if with_links:
|
|
52
|
+
link_cell.hyperlink = Hyperlink(
|
|
53
|
+
ref=link_cell.coordinate, target=docx_name, location=info["bookmark"], display="→定位Word表"
|
|
54
|
+
)
|
|
55
|
+
ws.cell(anchor_row, 6, f"列数:{info['ncols']}")
|
|
56
|
+
for col in range(1, 7):
|
|
57
|
+
cell = ws.cell(anchor_row, col)
|
|
58
|
+
cell.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True, color="1F4E79")
|
|
59
|
+
cell.fill = FILL_ANCHOR
|
|
60
|
+
cell.alignment = Alignment(horizontal="left" if col > 1 else "center", vertical="center")
|
|
61
|
+
|
|
62
|
+
grid_start = anchor_row + 1
|
|
63
|
+
nrows, ncols = info["nrows"], info["ncols"]
|
|
64
|
+
borders = info["borders"]
|
|
65
|
+
sides_cache: dict[tuple[int, int], dict] = {}
|
|
66
|
+
formulas = total_formula_cells(info, grid_start, col0=3) if totals_formula else {}
|
|
67
|
+
formula_count += len(formulas)
|
|
68
|
+
|
|
69
|
+
for r in range(nrows):
|
|
70
|
+
xlsx_row = grid_start + r
|
|
71
|
+
code_cell = ws.cell(xlsx_row, 1, code)
|
|
72
|
+
code_cell.fill = FILL_CODE_COLUMN
|
|
73
|
+
code_cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color="808080")
|
|
74
|
+
code_cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
75
|
+
if r == 0:
|
|
76
|
+
mark, mark_color = MARK_HEADER, "808080"
|
|
77
|
+
else:
|
|
78
|
+
has_content = any((info["text"][r][c] or "").strip() for c in range(1, ncols)) or any(
|
|
79
|
+
(xlsx_row, 3 + c) in formulas for c in range(1, ncols)
|
|
80
|
+
)
|
|
81
|
+
mark, mark_color = (MARK_YES, "008000") if has_content else (MARK_NO, "C00000")
|
|
82
|
+
mark_cell = ws.cell(xlsx_row, 2, mark)
|
|
83
|
+
mark_cell.font = Font(name=FONT_NAME, size=FONT_SIZE, color=mark_color)
|
|
84
|
+
mark_cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
85
|
+
for c in range(ncols):
|
|
86
|
+
pos = info["cellmap"][r][c]
|
|
87
|
+
sides_cache[(r, c)] = position_sides(borders, r, c, nrows, ncols)
|
|
88
|
+
if pos is None or not pos.owner:
|
|
89
|
+
continue
|
|
90
|
+
cell = ws.cell(xlsx_row, 3 + c)
|
|
91
|
+
value, number_format = to_excel_value(info["text"][r][c] or "")
|
|
92
|
+
horizontal, vertical, _ = cell_alignment(pos.tc)
|
|
93
|
+
formula = formulas.get((xlsx_row, 3 + c))
|
|
94
|
+
if formula is not None:
|
|
95
|
+
cell.value = formula
|
|
96
|
+
elif value is not None:
|
|
97
|
+
cell.value = value
|
|
98
|
+
if isinstance(value, str):
|
|
99
|
+
cell.data_type = "s" # Word 来源的 = 文本不是公式
|
|
100
|
+
cell.number_format = number_format or ("@" if isinstance(value, str) else "General")
|
|
101
|
+
cell.alignment = Alignment(
|
|
102
|
+
horizontal=horizontal, vertical=vertical, wrap_text=True if isinstance(value, str) and "\n" in value else False
|
|
103
|
+
)
|
|
104
|
+
cell.font = Font(name=FONT_NAME, size=FONT_SIZE)
|
|
105
|
+
sides = dict(sides_cache[(r, c)])
|
|
106
|
+
sides.update(explicit_borders(pos.tc))
|
|
107
|
+
cell.border = make_border(sides)
|
|
108
|
+
text_for_width = display_text(value, number_format) if value is not None else ""
|
|
109
|
+
longest = max((approx_width(part) for part in text_for_width.split("\n")), default=0.0)
|
|
110
|
+
widths[3 + c] = max(widths.get(3 + c, 8.0), min(longest + 2.0, 45.0))
|
|
111
|
+
|
|
112
|
+
for (r, c, rowspan, colspan) in info["merges"]:
|
|
113
|
+
if rowspan == 1 and colspan == 1:
|
|
114
|
+
continue
|
|
115
|
+
ws.merge_cells(
|
|
116
|
+
start_row=grid_start + r,
|
|
117
|
+
start_column=3 + c,
|
|
118
|
+
end_row=grid_start + r + rowspan - 1,
|
|
119
|
+
end_column=3 + c + colspan - 1,
|
|
120
|
+
)
|
|
121
|
+
top = sides_cache[(r, c)]["top"]
|
|
122
|
+
left = sides_cache[(r, c)]["left"]
|
|
123
|
+
bottom = sides_cache[(r + rowspan - 1, c + colspan - 1)]["bottom"]
|
|
124
|
+
right = sides_cache[(r + rowspan - 1, c + colspan - 1)]["right"]
|
|
125
|
+
anchor_cell = ws.cell(grid_start + r, 3 + c)
|
|
126
|
+
anchor_cell.border = make_border({"top": top, "left": left, "bottom": bottom, "right": right})
|
|
127
|
+
|
|
128
|
+
defined.append((f"EX_{code}", f"'{sheet_name}'!$C${grid_start}"))
|
|
129
|
+
row = grid_start + nrows + 1 # 表间空一行
|
|
130
|
+
|
|
131
|
+
ws.column_dimensions["B"].width = 6
|
|
132
|
+
for column, width in widths.items():
|
|
133
|
+
ws.column_dimensions[get_column_letter(column)].width = width
|
|
134
|
+
|
|
135
|
+
for name, ref in defined:
|
|
136
|
+
definition = DefinedName(name, attr_text=ref)
|
|
137
|
+
try:
|
|
138
|
+
wb.defined_names.add(definition)
|
|
139
|
+
except AttributeError: # 兼容旧版 openpyxl
|
|
140
|
+
wb.defined_names[name] = definition
|
|
141
|
+
if formula_count:
|
|
142
|
+
log(f"[导出] 合计行已写 {formula_count} 个求和公式(在 Excel 改明细后合计自动更新;同步时按公式结果回写 Word)")
|
|
143
|
+
return wb
|