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,265 @@
|
|
|
1
|
+
"""工作簿里的「链接标注」工作表:高亮标记的导出与回读。
|
|
2
|
+
|
|
3
|
+
列:标记 | 书签 | 位置 | 原文 | 新内容 | 链接地址 | →定位Word | 来源 | 登记序号
|
|
4
|
+
* 导出/刷新时按书签名保留已填的「新内容」「链接地址」;
|
|
5
|
+
* Word 中已删除的标记保留成行并在位置列标注「(Word 中已删除)」。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from openpyxl import load_workbook
|
|
13
|
+
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
|
14
|
+
from openpyxl.utils import get_column_letter
|
|
15
|
+
from openpyxl.worksheet.hyperlink import Hyperlink
|
|
16
|
+
|
|
17
|
+
from .config import FONT_NAME
|
|
18
|
+
|
|
19
|
+
SHEET_MARKS = "链接标注"
|
|
20
|
+
HEADERS = ["标记", "书签", "位置", "原文", "新内容", "链接地址", "→定位Word", "来源", "登记序号"]
|
|
21
|
+
HEADER_FILL = PatternFill("solid", fgColor="FFF2CC")
|
|
22
|
+
DELETED_FONT = Font(name=FONT_NAME, size=10, color="9AA3AF")
|
|
23
|
+
THIN = Side(style="thin", color="E3E6EA")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def read_previous_marks(xlsx_path: Path) -> list[dict]:
|
|
27
|
+
"""读取现有工作簿里「链接标注」工作表的历史内容(用于保留已填写项)。"""
|
|
28
|
+
if not xlsx_path.exists():
|
|
29
|
+
return []
|
|
30
|
+
try:
|
|
31
|
+
workbook = load_workbook(str(xlsx_path))
|
|
32
|
+
except Exception:
|
|
33
|
+
return []
|
|
34
|
+
if SHEET_MARKS not in workbook.sheetnames:
|
|
35
|
+
return []
|
|
36
|
+
return parse_marks_rows(workbook[SHEET_MARKS], resolve_formulas=False)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_marks_rows(ws, cached_ws=None, *, resolve_formulas: bool = True, zero_mode: str = "excel") -> list[dict]:
|
|
40
|
+
"""把工作表读成行字典;遇到「标记」列空行就停止。
|
|
41
|
+
|
|
42
|
+
「新内容」按单元格在 Excel 里的显示效果转换(与表格回写/占位符同口径):
|
|
43
|
+
日期按数字格式渲染(如 2025年12月31日),不会出现 2025-12-31 00:00:00;
|
|
44
|
+
金额千分位/小数位照显示。公式优先取 Excel 缓存结果,其次轻量求值。
|
|
45
|
+
"""
|
|
46
|
+
from .errors import SyncError
|
|
47
|
+
from .valuefmt import display_cell, formula_result
|
|
48
|
+
|
|
49
|
+
rows: list[dict] = []
|
|
50
|
+
seen_bookmarks: dict[str, int] = {}
|
|
51
|
+
if ws.max_row is None:
|
|
52
|
+
return rows
|
|
53
|
+
for row_index in range(2, ws.max_row + 1):
|
|
54
|
+
def raw_cell(column: int):
|
|
55
|
+
c = ws.cell(row_index, column)
|
|
56
|
+
raw = c.value
|
|
57
|
+
if resolve_formulas and isinstance(raw, str) and raw.startswith("="):
|
|
58
|
+
raw = formula_result(ws, row_index, column, cached_ws)
|
|
59
|
+
if raw is None:
|
|
60
|
+
raise SyncError(
|
|
61
|
+
f"「{SHEET_MARKS}」{c.coordinate} 是公式但没有可用的计算结果。"
|
|
62
|
+
"请先在 Excel 中打开该工作簿,完成重算并保存后再同步。"
|
|
63
|
+
)
|
|
64
|
+
return raw
|
|
65
|
+
|
|
66
|
+
def cell(column: int, display: bool = False) -> str:
|
|
67
|
+
c = ws.cell(row_index, column)
|
|
68
|
+
raw = raw_cell(column)
|
|
69
|
+
if display:
|
|
70
|
+
return display_cell(c, raw, zero_mode=zero_mode).strip()
|
|
71
|
+
return "" if raw is None else str(raw).strip()
|
|
72
|
+
|
|
73
|
+
label = cell(1)
|
|
74
|
+
if not label:
|
|
75
|
+
break
|
|
76
|
+
bookmark = cell(2)
|
|
77
|
+
if bookmark:
|
|
78
|
+
if bookmark in seen_bookmarks:
|
|
79
|
+
raise SyncError(
|
|
80
|
+
f"「{SHEET_MARKS}」书签 {bookmark} 重复出现在第 {seen_bookmarks[bookmark]} 行和第 {row_index} 行,"
|
|
81
|
+
"无法确定同步目标。请合并为一行后再同步。"
|
|
82
|
+
)
|
|
83
|
+
seen_bookmarks[bookmark] = row_index
|
|
84
|
+
sequence = ws.cell(row_index, 9).value
|
|
85
|
+
try:
|
|
86
|
+
sequence = int(sequence)
|
|
87
|
+
except (TypeError, ValueError):
|
|
88
|
+
sequence = row_index - 1
|
|
89
|
+
rows.append(
|
|
90
|
+
{
|
|
91
|
+
"row": row_index,
|
|
92
|
+
"label": label,
|
|
93
|
+
"bookmark": bookmark,
|
|
94
|
+
"position": cell(3),
|
|
95
|
+
"original": cell(4),
|
|
96
|
+
"new": cell(5, display=True),
|
|
97
|
+
"new_filled": bool(ws.cell(row_index, 5).value is not None and str(raw_cell(5)).strip()),
|
|
98
|
+
"link": cell(6),
|
|
99
|
+
"source": cell(8),
|
|
100
|
+
"sequence": sequence,
|
|
101
|
+
}
|
|
102
|
+
)
|
|
103
|
+
return rows
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def build_marks_sheet(
|
|
107
|
+
wb,
|
|
108
|
+
docx_name: str,
|
|
109
|
+
marks: list,
|
|
110
|
+
previous: list[dict],
|
|
111
|
+
processed: list[dict] | None = None,
|
|
112
|
+
) -> dict:
|
|
113
|
+
"""在 ``wb`` 中创建/刷新「链接标注」工作表,返回统计。
|
|
114
|
+
|
|
115
|
+
三类行:待处理(仍带高亮)→ 已处理(同步过、已去色,书签仍在)→ 已删除(Word 里连书签都没了)。
|
|
116
|
+
行号(M01…)按书签沿用上一版,保证 Excel 里引用稳定。
|
|
117
|
+
"""
|
|
118
|
+
previous_by_bookmark = {row["bookmark"]: row for row in previous if row["bookmark"]}
|
|
119
|
+
current = {mark.bookmark for mark in marks if mark.bookmark}
|
|
120
|
+
orphans = [row for row in previous if row["bookmark"] and row["bookmark"] not in current]
|
|
121
|
+
processed = processed or []
|
|
122
|
+
processed_names = {item["bookmark"] for item in processed}
|
|
123
|
+
orphans = [row for row in orphans if row["bookmark"] not in processed_names]
|
|
124
|
+
|
|
125
|
+
label_by_bookmark = {row["bookmark"]: row["label"] for row in previous if row["bookmark"]}
|
|
126
|
+
used_numbers = set()
|
|
127
|
+
for label in label_by_bookmark.values():
|
|
128
|
+
if isinstance(label, str) and label.startswith("M") and label[1:].isdigit():
|
|
129
|
+
used_numbers.add(int(label[1:]))
|
|
130
|
+
next_number = 1
|
|
131
|
+
|
|
132
|
+
def label_for(bookmark: str) -> str:
|
|
133
|
+
nonlocal next_number
|
|
134
|
+
if bookmark in label_by_bookmark:
|
|
135
|
+
return label_by_bookmark[bookmark]
|
|
136
|
+
while next_number in used_numbers:
|
|
137
|
+
next_number += 1
|
|
138
|
+
used_numbers.add(next_number)
|
|
139
|
+
label = f"M{next_number:02d}"
|
|
140
|
+
label_by_bookmark[bookmark] = label
|
|
141
|
+
return label
|
|
142
|
+
|
|
143
|
+
if SHEET_MARKS in wb.sheetnames:
|
|
144
|
+
ws = wb[SHEET_MARKS]
|
|
145
|
+
if ws.max_row:
|
|
146
|
+
ws.delete_rows(1, ws.max_row)
|
|
147
|
+
else:
|
|
148
|
+
ws = wb.create_sheet(SHEET_MARKS)
|
|
149
|
+
|
|
150
|
+
for column, title in enumerate(HEADERS, start=1):
|
|
151
|
+
cell = ws.cell(1, column, title)
|
|
152
|
+
cell.font = Font(name=FONT_NAME, size=10, bold=True, color="1F4E79")
|
|
153
|
+
cell.fill = HEADER_FILL
|
|
154
|
+
cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
155
|
+
cell.border = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
|
156
|
+
|
|
157
|
+
row_index = 2
|
|
158
|
+
for mark in marks:
|
|
159
|
+
old = previous_by_bookmark.get(mark.bookmark, {})
|
|
160
|
+
ws.cell(row_index, 1, label_for(mark.bookmark))
|
|
161
|
+
ws.cell(row_index, 2, mark.bookmark)
|
|
162
|
+
ws.cell(row_index, 3, mark.location)
|
|
163
|
+
ws.cell(row_index, 4, mark.text)
|
|
164
|
+
if old.get("new"):
|
|
165
|
+
ws.cell(row_index, 5, old["new"])
|
|
166
|
+
ws.cell(row_index, 6, old.get("link", ""))
|
|
167
|
+
ws.cell(row_index, 8, "全量")
|
|
168
|
+
ws.cell(row_index, 9, row_index - 1)
|
|
169
|
+
link_cell = ws.cell(row_index, 7, "→定位Word")
|
|
170
|
+
link_cell.hyperlink = Hyperlink(
|
|
171
|
+
ref=link_cell.coordinate, target=docx_name, location=mark.bookmark, display="→定位Word"
|
|
172
|
+
)
|
|
173
|
+
_style_row(ws, row_index)
|
|
174
|
+
row_index += 1
|
|
175
|
+
|
|
176
|
+
for item in processed:
|
|
177
|
+
old = previous_by_bookmark.get(item["bookmark"], {})
|
|
178
|
+
ws.cell(row_index, 1, label_for(item["bookmark"]))
|
|
179
|
+
ws.cell(row_index, 2, item["bookmark"])
|
|
180
|
+
ws.cell(row_index, 3, f"{item['location']}(已处理)")
|
|
181
|
+
ws.cell(row_index, 4, item["text"] or old.get("original", ""))
|
|
182
|
+
if old.get("new"):
|
|
183
|
+
ws.cell(row_index, 5, old["new"])
|
|
184
|
+
if old.get("link"):
|
|
185
|
+
ws.cell(row_index, 6, old["link"])
|
|
186
|
+
ws.cell(row_index, 7, "(已处理)")
|
|
187
|
+
ws.cell(row_index, 8, "全量")
|
|
188
|
+
ws.cell(row_index, 9, row_index - 1)
|
|
189
|
+
_style_row(ws, row_index, deleted=True)
|
|
190
|
+
row_index += 1
|
|
191
|
+
|
|
192
|
+
for orphan in orphans:
|
|
193
|
+
ws.cell(row_index, 1, label_for(orphan["bookmark"]) if orphan.get("bookmark") else orphan.get("label", ""))
|
|
194
|
+
ws.cell(row_index, 2, orphan.get("bookmark", ""))
|
|
195
|
+
position = (orphan.get("position") or "").replace("(Word 中已删除)", "")
|
|
196
|
+
ws.cell(row_index, 3, f"{position}(Word 中已删除)")
|
|
197
|
+
ws.cell(row_index, 4, orphan.get("original", ""))
|
|
198
|
+
if orphan.get("new"):
|
|
199
|
+
ws.cell(row_index, 5, orphan["new"])
|
|
200
|
+
if orphan.get("link"):
|
|
201
|
+
ws.cell(row_index, 6, orphan["link"])
|
|
202
|
+
ws.cell(row_index, 7, "(已删除)")
|
|
203
|
+
ws.cell(row_index, 8, "全量")
|
|
204
|
+
ws.cell(row_index, 9, row_index - 1)
|
|
205
|
+
_style_row(ws, row_index, deleted=True)
|
|
206
|
+
row_index += 1
|
|
207
|
+
|
|
208
|
+
for column, width in {1: 7, 2: 12, 3: 18, 4: 26, 5: 26, 6: 34, 7: 12, 8: 10, 9: 10}.items():
|
|
209
|
+
ws.column_dimensions[get_column_letter(column)].width = width
|
|
210
|
+
ws.freeze_panes = "A2"
|
|
211
|
+
return {"marks": len(marks), "processed": len(processed), "orphans": len(orphans)}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def append_marks_sheet(wb, docx_name: str, marks: list, previous: list[dict]) -> dict:
|
|
215
|
+
"""只追加新增标记;既有行、行号、公式和填写值完全不动。"""
|
|
216
|
+
known = {row.get("bookmark") for row in previous if row.get("bookmark")}
|
|
217
|
+
marks = [mark for mark in marks if not mark.bookmark or mark.bookmark not in known]
|
|
218
|
+
if not marks:
|
|
219
|
+
return {"marks": 0, "processed": 0, "orphans": 0}
|
|
220
|
+
if SHEET_MARKS in wb.sheetnames:
|
|
221
|
+
ws = wb[SHEET_MARKS]
|
|
222
|
+
else:
|
|
223
|
+
ws = wb.create_sheet(SHEET_MARKS)
|
|
224
|
+
previous = []
|
|
225
|
+
for column, title in enumerate(HEADERS, start=1):
|
|
226
|
+
cell = ws.cell(1, column, title)
|
|
227
|
+
cell.font = Font(name=FONT_NAME, size=10, bold=True, color="1F4E79")
|
|
228
|
+
cell.fill = HEADER_FILL
|
|
229
|
+
cell.alignment = Alignment(horizontal="center", vertical="center")
|
|
230
|
+
cell.border = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
|
231
|
+
known_labels = {str(row.get("label") or "") for row in previous}
|
|
232
|
+
next_number = 1
|
|
233
|
+
while f"XM{next_number:02d}" in known_labels:
|
|
234
|
+
next_number += 1
|
|
235
|
+
sequence = max([int(row.get("sequence") or 0) for row in previous] + [0]) + 1
|
|
236
|
+
added = 0
|
|
237
|
+
for mark in marks:
|
|
238
|
+
while f"XM{next_number:02d}" in known_labels:
|
|
239
|
+
next_number += 1
|
|
240
|
+
label = f"XM{next_number:02d}"
|
|
241
|
+
next_number += 1
|
|
242
|
+
known_labels.add(label)
|
|
243
|
+
row_index = max(ws.max_row or 1, 1) + 1
|
|
244
|
+
values = [label, mark.bookmark, mark.location, mark.text, "", "", "→定位Word", "增量", sequence]
|
|
245
|
+
for column, value in enumerate(values, start=1):
|
|
246
|
+
ws.cell(row_index, column, value)
|
|
247
|
+
link_cell = ws.cell(row_index, 7)
|
|
248
|
+
link_cell.hyperlink = Hyperlink(
|
|
249
|
+
ref=link_cell.coordinate, target=docx_name, location=mark.bookmark, display="→定位Word"
|
|
250
|
+
)
|
|
251
|
+
_style_row(ws, row_index)
|
|
252
|
+
sequence += 1
|
|
253
|
+
added += 1
|
|
254
|
+
for column, width in {1: 7, 2: 12, 3: 18, 4: 26, 5: 26, 6: 34, 7: 12, 8: 10, 9: 10}.items():
|
|
255
|
+
ws.column_dimensions[get_column_letter(column)].width = width
|
|
256
|
+
ws.freeze_panes = "A2"
|
|
257
|
+
return {"marks": added, "processed": 0, "orphans": 0}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _style_row(ws, row_index: int, deleted: bool = False) -> None:
|
|
261
|
+
for column in range(1, len(HEADERS) + 1):
|
|
262
|
+
cell = ws.cell(row_index, column)
|
|
263
|
+
cell.font = DELETED_FONT if deleted else Font(name=FONT_NAME, size=10)
|
|
264
|
+
cell.alignment = Alignment(vertical="center", wrap_text=column in (3, 4, 5, 6))
|
|
265
|
+
cell.border = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""导出时给合计行写求和公式:改明细后合计自动更新。
|
|
2
|
+
|
|
3
|
+
口径:首列以「合计」开头的行视为合计行;对每个数值列写 =SUM(数据区首行:数据区末行),
|
|
4
|
+
数据区 = 表头之后、该合计行之前。表头按 w:tblHeader 标记识别,未标记时按首行。
|
|
5
|
+
文字列(如备注)与「—」等占位文字不写公式,保留原样。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from openpyxl.utils import get_column_letter
|
|
11
|
+
|
|
12
|
+
from .valuefmt import to_excel_value
|
|
13
|
+
|
|
14
|
+
TOTAL_PREFIX = "合计"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _is_number(text: str) -> bool:
|
|
18
|
+
value, _ = to_excel_value(text or "")
|
|
19
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def total_formula_cells(info: dict, grid_start: int, col0: int = 2) -> dict[tuple[int, int], str]:
|
|
23
|
+
"""返回合计行应写 SUM 公式的单元格 {(Excel行, Excel列): 公式}。
|
|
24
|
+
|
|
25
|
+
grid_start 为该表网格首行(表头)在工作表中的行号;col0 为网格首列列号。
|
|
26
|
+
仅对合计行里本身是数字或空、且数据区出现过数字的列写公式;合并掉的非 owner 格、文字占位格跳过。
|
|
27
|
+
"""
|
|
28
|
+
text = info["text"]
|
|
29
|
+
nrows, ncols = info["nrows"], info["ncols"]
|
|
30
|
+
cellmap = info["cellmap"]
|
|
31
|
+
header = info.get("header_rows") or set()
|
|
32
|
+
data_start = (max(header) + 1) if header else 1
|
|
33
|
+
formulas: dict[tuple[int, int], str] = {}
|
|
34
|
+
for t in range(nrows):
|
|
35
|
+
if not (text[t][0] or "").strip().startswith(TOTAL_PREFIX):
|
|
36
|
+
continue
|
|
37
|
+
data_end = t - 1
|
|
38
|
+
if data_end < data_start:
|
|
39
|
+
continue
|
|
40
|
+
for c in range(1, ncols):
|
|
41
|
+
pos = cellmap[t][c]
|
|
42
|
+
if pos is None or not pos.owner:
|
|
43
|
+
continue
|
|
44
|
+
total_value, _ = to_excel_value(text[t][c] or "")
|
|
45
|
+
if isinstance(total_value, str): # 「—」等占位文字,保留原样
|
|
46
|
+
continue
|
|
47
|
+
if not any(_is_number(text[r][c]) for r in range(data_start, data_end + 1)):
|
|
48
|
+
continue
|
|
49
|
+
letter = get_column_letter(col0 + c)
|
|
50
|
+
formulas[(grid_start + t, col0 + c)] = (
|
|
51
|
+
f"=SUM({letter}{grid_start + data_start}:{letter}{grid_start + data_end})"
|
|
52
|
+
)
|
|
53
|
+
return formulas
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""文件操作:路径解析、写前备份、占用检测、未指定文件时的自动识别。"""
|
|
2
|
+
|
|
3
|
+
import datetime as _dt
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from .console import log, warn
|
|
10
|
+
from .errors import SyncError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def project_root() -> Path:
|
|
14
|
+
"""项目根目录;打包 exe 时为 exe 所在目录(约定:本项目文件不落项目外)。"""
|
|
15
|
+
if getattr(sys, "frozen", False):
|
|
16
|
+
return Path(sys.executable).resolve().parent
|
|
17
|
+
return Path(__file__).resolve().parents[2]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def tmp_root() -> Path:
|
|
21
|
+
"""项目内临时/工作目录(.tmp,已 gitignore),替代系统 Temp。"""
|
|
22
|
+
root = project_root() / ".tmp"
|
|
23
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
return root
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def resolve_docx(path_text: str) -> Path:
|
|
28
|
+
path = Path(path_text).expanduser().resolve()
|
|
29
|
+
if not path.exists():
|
|
30
|
+
raise SyncError(f"找不到 Word 文件:{path}")
|
|
31
|
+
if path.suffix.lower() not in (".docx", ".docm"):
|
|
32
|
+
raise SyncError(f"只支持 .docx/.docm 文件:{path}")
|
|
33
|
+
return path
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def resolve_xlsx(docx_path: Path, excel_text: str | None) -> Path:
|
|
37
|
+
if excel_text:
|
|
38
|
+
return Path(excel_text).expanduser().resolve()
|
|
39
|
+
return docx_path.with_name(f"{docx_path.stem}_表格数据.xlsx")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def find_default_docx(base_dir: Path) -> Path:
|
|
43
|
+
"""在指定目录里找唯一的 .docx(忽略 Word 临时文件)。"""
|
|
44
|
+
candidates = sorted(
|
|
45
|
+
path for path in base_dir.glob("*.docx") if path.is_file() and not path.name.startswith("~$")
|
|
46
|
+
)
|
|
47
|
+
if not candidates:
|
|
48
|
+
raise SyncError(f"未在当前目录找到 .docx 文件,请把报告放到:{base_dir},或显式指定文件路径")
|
|
49
|
+
if len(candidates) > 1:
|
|
50
|
+
names = "\n ".join(path.name for path in candidates)
|
|
51
|
+
raise SyncError(f"当前目录有多个 .docx,请显式指定要处理哪一个:\n {names}")
|
|
52
|
+
return candidates[0]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def default_base_dir(script_dir: Path) -> Path:
|
|
56
|
+
"""入口的“工作目录”:当前目录里有 .docx 就用当前目录,否则用入口所在目录。
|
|
57
|
+
|
|
58
|
+
这样既能“双击界面(入口目录=工作目录)”,也能“在报告目录里直接运行命令行 exe”。
|
|
59
|
+
"""
|
|
60
|
+
try:
|
|
61
|
+
cwd = Path.cwd()
|
|
62
|
+
except OSError:
|
|
63
|
+
return script_dir
|
|
64
|
+
if cwd != script_dir:
|
|
65
|
+
try:
|
|
66
|
+
if any(p.is_file() and not p.name.startswith("~$") for p in cwd.glob("*.docx")):
|
|
67
|
+
return cwd
|
|
68
|
+
except OSError:
|
|
69
|
+
return script_dir
|
|
70
|
+
return script_dir
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def fill_docx_argument(argv: list[str], base_dir: Path) -> list[str]:
|
|
74
|
+
"""未显式给出 Word 文件时,自动补上目录里唯一的 .docx。"""
|
|
75
|
+
if argv and not argv[0].startswith("-"):
|
|
76
|
+
return argv
|
|
77
|
+
docx_path = find_default_docx(base_dir)
|
|
78
|
+
log(f"未指定文件,已自动使用:{docx_path.name}")
|
|
79
|
+
return [str(docx_path), *argv]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def check_file_free(path: Path, force: bool) -> None:
|
|
83
|
+
"""独占写测试;文件被 Word/Excel 打开时给出中文提示。"""
|
|
84
|
+
if not path.exists():
|
|
85
|
+
return
|
|
86
|
+
lock_names = {f"~${path.name}", f"~${path.name[2:]}"}
|
|
87
|
+
stale_lock = any((path.parent / name).exists() for name in lock_names)
|
|
88
|
+
try:
|
|
89
|
+
with open(path, "r+b"):
|
|
90
|
+
pass
|
|
91
|
+
except OSError:
|
|
92
|
+
if force:
|
|
93
|
+
warn(f"{path.name} 似乎正被其他程序占用,已按 --force 继续(可能失败)")
|
|
94
|
+
else:
|
|
95
|
+
raise SyncError(
|
|
96
|
+
f"{path.name} 正被其他程序占用,请先关闭 Word/Excel 后重试(或加 --force 强制继续)"
|
|
97
|
+
)
|
|
98
|
+
else:
|
|
99
|
+
if stale_lock:
|
|
100
|
+
warn(f"{path.name} 存在残留的临时锁文件(文件本身未被占用),已忽略并继续")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def backup_file(path: Path) -> Path | None:
|
|
104
|
+
"""落盘前备份到同目录 _backup,文件名带时间戳。"""
|
|
105
|
+
if not path.exists():
|
|
106
|
+
return None
|
|
107
|
+
backup_dir = path.parent / "_backup"
|
|
108
|
+
backup_dir.mkdir(exist_ok=True)
|
|
109
|
+
stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
110
|
+
target = backup_dir / f"{path.stem}.{stamp}.bak{path.suffix}"
|
|
111
|
+
counter = 1
|
|
112
|
+
while target.exists():
|
|
113
|
+
target = backup_dir / f"{path.stem}.{stamp}_{counter}.bak{path.suffix}"
|
|
114
|
+
counter += 1
|
|
115
|
+
shutil.copy2(path, target)
|
|
116
|
+
return target
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def load_workbook_for_save(path: Path, **kwargs):
|
|
120
|
+
"""读取待修改工作簿;.xlsm 保留 VBA,避免工具写回时丢宏。"""
|
|
121
|
+
from openpyxl import load_workbook
|
|
122
|
+
|
|
123
|
+
if str(path).lower().endswith(".xlsm"):
|
|
124
|
+
kwargs["keep_vba"] = True
|
|
125
|
+
return load_workbook(str(path), **kwargs)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _stage_office_file(path: Path, save, validate) -> dict:
|
|
129
|
+
fd, temp_name = tempfile.mkstemp(prefix=f".{path.stem}.", suffix=path.suffix, dir=path.parent)
|
|
130
|
+
os.close(fd)
|
|
131
|
+
staged = Path(temp_name)
|
|
132
|
+
rollback = None
|
|
133
|
+
try:
|
|
134
|
+
save(staged)
|
|
135
|
+
validate(staged)
|
|
136
|
+
existed = path.exists()
|
|
137
|
+
if existed:
|
|
138
|
+
fd, rollback_name = tempfile.mkstemp(prefix=f".{path.stem}.rollback.", suffix=path.suffix, dir=path.parent)
|
|
139
|
+
os.close(fd)
|
|
140
|
+
rollback = Path(rollback_name)
|
|
141
|
+
shutil.copy2(path, rollback)
|
|
142
|
+
return {"path": path, "new": staged, "old": rollback, "backup": None, "keep_old": False, "existed": existed}
|
|
143
|
+
except Exception:
|
|
144
|
+
staged.unlink(missing_ok=True)
|
|
145
|
+
if rollback is not None:
|
|
146
|
+
rollback.unlink(missing_ok=True)
|
|
147
|
+
raise
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def save_docx_xlsx_transaction(
|
|
151
|
+
*,
|
|
152
|
+
docx_path: Path | None = None,
|
|
153
|
+
doc=None,
|
|
154
|
+
xlsx_path: Path | None = None,
|
|
155
|
+
wb=None,
|
|
156
|
+
backup: bool = True,
|
|
157
|
+
) -> dict[Path, Path | None]:
|
|
158
|
+
"""先序列化并校验 Word/Excel,再成对替换;第二步失败时恢复第一步。"""
|
|
159
|
+
import docx
|
|
160
|
+
from openpyxl import load_workbook
|
|
161
|
+
|
|
162
|
+
staged: list[dict] = []
|
|
163
|
+
|
|
164
|
+
def validate_xlsx(path: Path) -> None:
|
|
165
|
+
check = load_workbook(str(path), read_only=True, data_only=False)
|
|
166
|
+
try:
|
|
167
|
+
if not check.sheetnames:
|
|
168
|
+
raise ValueError("工作簿没有工作表")
|
|
169
|
+
finally:
|
|
170
|
+
check.close()
|
|
171
|
+
|
|
172
|
+
def validate_docx(path: Path) -> None:
|
|
173
|
+
docx.Document(str(path))
|
|
174
|
+
|
|
175
|
+
try:
|
|
176
|
+
if xlsx_path is not None:
|
|
177
|
+
staged.append(_stage_office_file(xlsx_path, lambda path: wb.save(str(path)), validate_xlsx))
|
|
178
|
+
if docx_path is not None:
|
|
179
|
+
staged.append(_stage_office_file(docx_path, lambda path: doc.save(str(path)), validate_docx))
|
|
180
|
+
if backup:
|
|
181
|
+
for item in staged:
|
|
182
|
+
item["backup"] = backup_file(item["path"])
|
|
183
|
+
|
|
184
|
+
replaced: list[dict] = []
|
|
185
|
+
for item in staged:
|
|
186
|
+
try:
|
|
187
|
+
os.replace(item["new"], item["path"])
|
|
188
|
+
except OSError as exc:
|
|
189
|
+
rollback_errors = []
|
|
190
|
+
for previous in reversed(replaced):
|
|
191
|
+
try:
|
|
192
|
+
if previous["existed"]:
|
|
193
|
+
os.replace(previous["old"], previous["path"])
|
|
194
|
+
else:
|
|
195
|
+
previous["path"].unlink(missing_ok=True)
|
|
196
|
+
previous["old"] = None
|
|
197
|
+
except OSError as rollback_exc:
|
|
198
|
+
previous["keep_old"] = True
|
|
199
|
+
rollback_errors.append(f"{previous['path'].name}({rollback_exc})")
|
|
200
|
+
if rollback_errors:
|
|
201
|
+
kept = "、".join(str(previous["old"]) for previous in replaced if previous["keep_old"])
|
|
202
|
+
raise SyncError(
|
|
203
|
+
f"保存 {item['path'].name} 失败,且自动回滚失败:{'、'.join(rollback_errors)}。"
|
|
204
|
+
f"原文件副本保留在:{kept}"
|
|
205
|
+
) from exc
|
|
206
|
+
raise SyncError(f"保存 {item['path'].name} 失败,Word/Excel 已恢复为同步前状态:{exc}") from exc
|
|
207
|
+
item["new"] = None
|
|
208
|
+
replaced.append(item)
|
|
209
|
+
return {item["path"]: item["backup"] for item in staged}
|
|
210
|
+
except SyncError:
|
|
211
|
+
raise
|
|
212
|
+
except Exception as exc:
|
|
213
|
+
raise SyncError(f"保存前校验或备份失败,Word/Excel 均未替换:{exc}") from exc
|
|
214
|
+
finally:
|
|
215
|
+
for item in staged:
|
|
216
|
+
if item["new"] is not None:
|
|
217
|
+
item["new"].unlink(missing_ok=True)
|
|
218
|
+
if item["old"] is not None and not item["keep_old"]:
|
|
219
|
+
item["old"].unlink(missing_ok=True)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""桌面界面(PySide6):把各功能内置成页面,左侧导航切换。
|
|
2
|
+
|
|
3
|
+
启动方式:
|
|
4
|
+
python -m wesync.gui 或双击 审计工具箱.pyw
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _install_translation(app):
|
|
13
|
+
from PySide6 import __file__ as pyside_file
|
|
14
|
+
from PySide6.QtCore import QTranslator
|
|
15
|
+
|
|
16
|
+
class _ChineseTranslator(QTranslator):
|
|
17
|
+
def translate(self, context, sourceText, disambiguation=None, n=-1):
|
|
18
|
+
text = super().translate(context, sourceText, disambiguation, n)
|
|
19
|
+
if text or "&" not in sourceText:
|
|
20
|
+
return text
|
|
21
|
+
return super().translate(context, sourceText.replace("&", ""), disambiguation, n)
|
|
22
|
+
|
|
23
|
+
translator = _ChineseTranslator(app)
|
|
24
|
+
path = Path(pyside_file).parent / "translations" / "qtbase_zh_CN.qm"
|
|
25
|
+
if not translator.load(str(path)):
|
|
26
|
+
raise RuntimeError(f"缺少简体中文界面资源:{path}")
|
|
27
|
+
app.installTranslator(translator)
|
|
28
|
+
return translator
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def run(base_dir: Path | None = None) -> int:
|
|
32
|
+
"""启动界面主循环,返回进程退出码。"""
|
|
33
|
+
from PySide6.QtCore import Qt
|
|
34
|
+
from PySide6.QtGui import QIcon
|
|
35
|
+
from PySide6.QtWidgets import QApplication
|
|
36
|
+
|
|
37
|
+
from .app import WesyncApp
|
|
38
|
+
from .resources import icon_path
|
|
39
|
+
|
|
40
|
+
# 按系统实际缩放比例渲染(150% 即 1.5 倍)。不能用 Round:它会把 150% 取整成 2 倍,
|
|
41
|
+
# 字体在一部分高分屏电脑上显得异常大;Qt6 支持分数缩放,不必担心半像素发虚。
|
|
42
|
+
QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
|
|
43
|
+
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeDialogs, True)
|
|
44
|
+
app = QApplication.instance() or QApplication([])
|
|
45
|
+
_install_translation(app)
|
|
46
|
+
app.setApplicationName("审计工具箱")
|
|
47
|
+
app.setWindowIcon(QIcon(str(icon_path())))
|
|
48
|
+
window = WesyncApp(base_dir=base_dir)
|
|
49
|
+
window.show()
|
|
50
|
+
return app.exec()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
__all__ = ["run"]
|