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,220 @@
|
|
|
1
|
+
"""新表创建层:按 Excel 网格造标准样式的 Word 表格,插到指定表格之后(带表标题段落)。
|
|
2
|
+
|
|
3
|
+
样式与导出观感一致:宋体 9、上下细线内部点线、列宽按 Excel 列宽比例分配页面宽度;
|
|
4
|
+
首行为表头(加粗 + tblHeader),首列以「合计」开头的末行加粗;支持 gridSpan/vMerge。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
|
|
11
|
+
from docx.oxml import OxmlElement
|
|
12
|
+
from docx.oxml.ns import qn
|
|
13
|
+
from openpyxl.utils import get_column_letter
|
|
14
|
+
|
|
15
|
+
from .config import FONT_NAME, FONT_SIZE, NUMBER_RE
|
|
16
|
+
from .docx_grid import para_first_run_rpr, para_text
|
|
17
|
+
|
|
18
|
+
EMU_PER_DXA = 635
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _el(tag: str, **attrs):
|
|
22
|
+
el = OxmlElement(tag)
|
|
23
|
+
for key, value in attrs.items():
|
|
24
|
+
el.set(qn(f"w:{key}"), str(value))
|
|
25
|
+
return el
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _run(text: str, bold: bool):
|
|
29
|
+
r = _el("w:r")
|
|
30
|
+
rpr = _el("w:rPr")
|
|
31
|
+
rpr.append(_el("w:rFonts", ascii="Times New Roman", hAnsi="Times New Roman", eastAsia=FONT_NAME))
|
|
32
|
+
if bold:
|
|
33
|
+
rpr.append(_el("w:b"))
|
|
34
|
+
rpr.append(_el("w:sz", val=FONT_SIZE * 2))
|
|
35
|
+
rpr.append(_el("w:szCs", val=FONT_SIZE * 2))
|
|
36
|
+
r.append(rpr)
|
|
37
|
+
t = _el("w:t")
|
|
38
|
+
t.set(qn("xml:space"), "preserve")
|
|
39
|
+
t.text = text
|
|
40
|
+
r.append(t)
|
|
41
|
+
return r
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _cell_paragraphs(text: str, bold: bool, align: str) -> list:
|
|
45
|
+
parts = text.split("\n") if text else [""]
|
|
46
|
+
result = []
|
|
47
|
+
for part in parts:
|
|
48
|
+
p = _el("w:p")
|
|
49
|
+
ppr = _el("w:pPr")
|
|
50
|
+
ppr.append(_el("w:jc", val=align))
|
|
51
|
+
p.append(ppr)
|
|
52
|
+
if part:
|
|
53
|
+
p.append(_run(part, bold))
|
|
54
|
+
result.append(p)
|
|
55
|
+
return result
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _table_borders_el():
|
|
59
|
+
borders = _el("w:tblBorders")
|
|
60
|
+
for side, val in (("top", "single"), ("left", "nil"), ("bottom", "single"),
|
|
61
|
+
("right", "nil"), ("insideH", "dotted"), ("insideV", "dotted")):
|
|
62
|
+
borders.append(_el(f"w:{side}", val=val, sz=4, space=0, color="auto"))
|
|
63
|
+
return borders
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def available_width_dxa(doc) -> int:
|
|
67
|
+
try:
|
|
68
|
+
sec = doc.sections[0]
|
|
69
|
+
return max(2000, int((sec.page_width - sec.left_margin - sec.right_margin) / EMU_PER_DXA))
|
|
70
|
+
except Exception:
|
|
71
|
+
return 9000
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def col_widths_from_excel(ws, ncols: int, total_dxa: int, col0: int = 2) -> list[int]:
|
|
75
|
+
widths = []
|
|
76
|
+
for c in range(ncols):
|
|
77
|
+
letter = get_column_letter(col0 + c)
|
|
78
|
+
dim = ws.column_dimensions.get(letter)
|
|
79
|
+
widths.append(float(dim.width) if dim is not None and dim.width else 8.43)
|
|
80
|
+
total = sum(widths) or 1.0
|
|
81
|
+
result = [max(400, int(total_dxa * w / total)) for w in widths]
|
|
82
|
+
result[-1] += total_dxa - sum(result)
|
|
83
|
+
return result
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def build_table(grid: list[list[str]], merges: list[tuple[int, int, int, int]],
|
|
87
|
+
ncols: int, col_widths: list[int]):
|
|
88
|
+
"""按网格文本与合并区造 w:tbl。grid 非起点位置的文字被忽略。"""
|
|
89
|
+
nrows = len(grid)
|
|
90
|
+
span_of: dict[tuple[int, int], tuple[int, int]] = {}
|
|
91
|
+
hcovered: set[tuple[int, int]] = set()
|
|
92
|
+
vcont: dict[tuple[int, int], int] = {}
|
|
93
|
+
for (r, c, rs, cs) in merges:
|
|
94
|
+
span_of[(r, c)] = (rs, cs)
|
|
95
|
+
for k in range(1, cs):
|
|
96
|
+
hcovered.add((r, c + k))
|
|
97
|
+
for rr in range(r + 1, r + rs):
|
|
98
|
+
vcont[(rr, c)] = cs
|
|
99
|
+
for k in range(1, cs):
|
|
100
|
+
hcovered.add((rr, c + k))
|
|
101
|
+
|
|
102
|
+
total_row = nrows - 1 if nrows and grid[-1] and grid[-1][0].strip().startswith("合计") else -1
|
|
103
|
+
|
|
104
|
+
tbl = _el("w:tbl")
|
|
105
|
+
tblpr = _el("w:tblPr")
|
|
106
|
+
tblpr.append(_el("w:tblW", w=sum(col_widths), type="dxa"))
|
|
107
|
+
tblpr.append(_table_borders_el())
|
|
108
|
+
tblpr.append(_el("w:tblLayout", type="fixed"))
|
|
109
|
+
tbl.append(tblpr)
|
|
110
|
+
tblgrid = _el("w:tblGrid")
|
|
111
|
+
for width in col_widths:
|
|
112
|
+
tblgrid.append(_el("w:gridCol", w=width))
|
|
113
|
+
tbl.append(tblgrid)
|
|
114
|
+
|
|
115
|
+
for r in range(nrows):
|
|
116
|
+
tr = _el("w:tr")
|
|
117
|
+
if r == 0:
|
|
118
|
+
trpr = _el("w:trPr")
|
|
119
|
+
trpr.append(_el("w:tblHeader"))
|
|
120
|
+
tr.append(trpr)
|
|
121
|
+
bold_row = r == 0 or r == total_row
|
|
122
|
+
c = 0
|
|
123
|
+
while c < ncols:
|
|
124
|
+
if (r, c) in hcovered:
|
|
125
|
+
c += 1
|
|
126
|
+
continue
|
|
127
|
+
if (r, c) in vcont:
|
|
128
|
+
cs = vcont[(r, c)]
|
|
129
|
+
tc = _el("w:tc")
|
|
130
|
+
tcpr = _el("w:tcPr")
|
|
131
|
+
tcpr.append(_el("w:tcW", w=sum(col_widths[c:c + cs]), type="dxa"))
|
|
132
|
+
if cs > 1:
|
|
133
|
+
tcpr.append(_el("w:gridSpan", val=cs))
|
|
134
|
+
tcpr.append(_el("w:vMerge"))
|
|
135
|
+
tcpr.append(_el("w:vAlign", val="center"))
|
|
136
|
+
tc.append(tcpr)
|
|
137
|
+
tc.append(_el("w:p"))
|
|
138
|
+
tr.append(tc)
|
|
139
|
+
c += cs
|
|
140
|
+
continue
|
|
141
|
+
rs, cs = span_of.get((r, c), (1, 1))
|
|
142
|
+
text = grid[r][c] if c < len(grid[r]) else ""
|
|
143
|
+
tc = _el("w:tc")
|
|
144
|
+
tcpr = _el("w:tcPr")
|
|
145
|
+
tcpr.append(_el("w:tcW", w=sum(col_widths[c:c + cs]), type="dxa"))
|
|
146
|
+
if cs > 1:
|
|
147
|
+
tcpr.append(_el("w:gridSpan", val=cs))
|
|
148
|
+
if rs > 1:
|
|
149
|
+
tcpr.append(_el("w:vMerge", val="restart"))
|
|
150
|
+
tcpr.append(_el("w:vAlign", val="center"))
|
|
151
|
+
tc.append(tcpr)
|
|
152
|
+
if r == 0:
|
|
153
|
+
align = "center"
|
|
154
|
+
elif NUMBER_RE.match(text.strip()):
|
|
155
|
+
align = "right"
|
|
156
|
+
else:
|
|
157
|
+
align = "left"
|
|
158
|
+
for p in _cell_paragraphs(text, bold_row, align):
|
|
159
|
+
tc.append(p)
|
|
160
|
+
tr.append(tc)
|
|
161
|
+
c += cs
|
|
162
|
+
tbl.append(tr)
|
|
163
|
+
return tbl
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _caption_source_p(prev_tbl):
|
|
167
|
+
"""前一张表上方最近的非空段落,作为新表标题的格式样板。"""
|
|
168
|
+
if prev_tbl is None:
|
|
169
|
+
return None
|
|
170
|
+
node = prev_tbl.getprevious()
|
|
171
|
+
while node is not None and node.tag == qn("w:p"):
|
|
172
|
+
if para_text(node).strip():
|
|
173
|
+
return node
|
|
174
|
+
node = node.getprevious()
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _caption_paragraph(text: str, source_p):
|
|
179
|
+
p = _el("w:p")
|
|
180
|
+
if source_p is not None:
|
|
181
|
+
ppr = source_p.find(qn("w:pPr"))
|
|
182
|
+
if ppr is not None:
|
|
183
|
+
p.append(copy.deepcopy(ppr))
|
|
184
|
+
rpr = para_first_run_rpr(source_p)
|
|
185
|
+
r = _el("w:r")
|
|
186
|
+
if rpr is not None:
|
|
187
|
+
r.append(rpr)
|
|
188
|
+
else:
|
|
189
|
+
default_rpr = _el("w:rPr")
|
|
190
|
+
default_rpr.append(_el("w:rFonts", ascii="Times New Roman", hAnsi="Times New Roman", eastAsia=FONT_NAME))
|
|
191
|
+
default_rpr.append(_el("w:sz", val=21))
|
|
192
|
+
r.append(default_rpr)
|
|
193
|
+
t = _el("w:t")
|
|
194
|
+
t.set(qn("xml:space"), "preserve")
|
|
195
|
+
t.text = text
|
|
196
|
+
r.append(t)
|
|
197
|
+
p.append(r)
|
|
198
|
+
return p
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def insert_new_table(doc, prev_tbl, tbl, caption_text: str) -> None:
|
|
202
|
+
"""把新表插到 prev_tbl 之后(无 prev_tbl 时插到文档末尾),前面带标题段落。
|
|
203
|
+
|
|
204
|
+
Word 要求两张表之间、以及文档末尾的表之后必须有段落,这里一并补齐。
|
|
205
|
+
"""
|
|
206
|
+
caption = _caption_paragraph(caption_text, _caption_source_p(prev_tbl))
|
|
207
|
+
if prev_tbl is not None and prev_tbl.getparent() is not None:
|
|
208
|
+
prev_tbl.addnext(caption)
|
|
209
|
+
caption.addnext(tbl)
|
|
210
|
+
else:
|
|
211
|
+
body = doc.element.body
|
|
212
|
+
sectpr = body.find(qn("w:sectPr"))
|
|
213
|
+
if sectpr is not None:
|
|
214
|
+
sectpr.addprevious(caption)
|
|
215
|
+
else:
|
|
216
|
+
body.append(caption)
|
|
217
|
+
caption.addnext(tbl)
|
|
218
|
+
nxt = tbl.getnext()
|
|
219
|
+
if nxt is None or nxt.tag in (qn("w:tbl"), qn("w:sectPr")):
|
|
220
|
+
tbl.addnext(_el("w:p"))
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""正文占位符:扫描/替换 Word 正文与页眉页脚里的 {字段名},值来自工作簿「正文信息」表。
|
|
2
|
+
|
|
3
|
+
替换只动占位符文字,保留所在 run 的字体格式;跨 run 的占位符也能整体替换。
|
|
4
|
+
未填值的占位符不替换(由调用方决定跳过该份报告)。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
PLACEHOLDER_RE = re.compile(r"\{([^{}\r\n]{1,40})\}")
|
|
12
|
+
VALUES_SHEET = "正文信息"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PlaceholderValues(dict[str, str]):
|
|
16
|
+
def __init__(self, filled_fields: set[str]):
|
|
17
|
+
super().__init__()
|
|
18
|
+
self.filled_fields = filled_fields
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _iter_paragraphs(doc):
|
|
22
|
+
"""正文与页眉页脚的直接段落;表格内占位符不参与。"""
|
|
23
|
+
yield from doc.paragraphs
|
|
24
|
+
for section in doc.sections:
|
|
25
|
+
for part in (section.header, section.footer,
|
|
26
|
+
section.first_page_header, section.first_page_footer,
|
|
27
|
+
section.even_page_header, section.even_page_footer):
|
|
28
|
+
if part is not None:
|
|
29
|
+
yield from part.paragraphs
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def scan_placeholders(doc) -> list[str]:
|
|
33
|
+
"""按出现顺序去重列出全部占位符字段名。"""
|
|
34
|
+
seen: dict[str, None] = {}
|
|
35
|
+
for p in _iter_paragraphs(doc):
|
|
36
|
+
for m in PLACEHOLDER_RE.finditer(p.text):
|
|
37
|
+
field = m.group(1).strip()
|
|
38
|
+
if field:
|
|
39
|
+
seen.setdefault(field, None)
|
|
40
|
+
return list(seen)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _replace_in_paragraph(p, values: dict[str, str]) -> list[tuple[str, str]]:
|
|
44
|
+
runs = p.runs
|
|
45
|
+
if not runs:
|
|
46
|
+
return []
|
|
47
|
+
full = "".join(r.text for r in runs)
|
|
48
|
+
matches = [m for m in PLACEHOLDER_RE.finditer(full) if m.group(1).strip() in values]
|
|
49
|
+
if not matches:
|
|
50
|
+
return []
|
|
51
|
+
spans = []
|
|
52
|
+
pos = 0
|
|
53
|
+
for r in runs:
|
|
54
|
+
spans.append((pos, pos + len(r.text)))
|
|
55
|
+
pos += len(r.text)
|
|
56
|
+
done = []
|
|
57
|
+
for m in reversed(matches): # 从右往左改,前面的偏移不受影响
|
|
58
|
+
field = m.group(1).strip()
|
|
59
|
+
replacement = values[field]
|
|
60
|
+
s, e = m.span()
|
|
61
|
+
first = True
|
|
62
|
+
for r, (rs, re_) in zip(runs, spans):
|
|
63
|
+
if re_ <= s or rs >= e:
|
|
64
|
+
continue
|
|
65
|
+
head = r.text[: max(0, s - rs)] if first else ""
|
|
66
|
+
tail = r.text[max(0, min(len(r.text), e - rs)):]
|
|
67
|
+
r.text = head + (replacement if first else "") + tail
|
|
68
|
+
first = False
|
|
69
|
+
done.append((field, replacement))
|
|
70
|
+
return list(reversed(done))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def apply_placeholders(doc, values: dict[str, str], *, dry_run: bool = False) -> dict:
|
|
74
|
+
"""返回 {"replaced": [(字段, 新值)], "missing": [字段]};dry_run 只列计划不改文档。"""
|
|
75
|
+
fields = scan_placeholders(doc)
|
|
76
|
+
filled = getattr(
|
|
77
|
+
values,
|
|
78
|
+
"filled_fields",
|
|
79
|
+
{key for key, value in values.items() if str(value).strip()},
|
|
80
|
+
)
|
|
81
|
+
missing = [f for f in fields if f not in filled]
|
|
82
|
+
if dry_run:
|
|
83
|
+
return {"replaced": [(f, str(values[f])) for f in fields if f not in missing], "missing": missing}
|
|
84
|
+
replaced = []
|
|
85
|
+
effective = {f: str(values[f]) for f in fields if f not in missing}
|
|
86
|
+
for p in _iter_paragraphs(doc):
|
|
87
|
+
replaced.extend(_replace_in_paragraph(p, effective))
|
|
88
|
+
return {"replaced": replaced, "missing": missing}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def read_placeholder_values(
|
|
92
|
+
xlsx_path, *, resolve_formulas: bool = True, zero_mode: str = "excel",
|
|
93
|
+
wb=None, cached_wb=None,
|
|
94
|
+
) -> PlaceholderValues:
|
|
95
|
+
"""读工作簿「正文信息」表(A=字段 B=值,首行表头);无该表返回空。
|
|
96
|
+
|
|
97
|
+
值按单元格在 Excel 里的显示效果转换(与表格回写同口径):日期用其数字格式渲染
|
|
98
|
+
(如 2026-12-31、2026年12月31日),不会出现 "2026-12-31 00:00:00" 这类原始值。
|
|
99
|
+
公式优先取 Excel 缓存结果,其次轻量求值;导出保留旧值时可按原公式保留。
|
|
100
|
+
"""
|
|
101
|
+
from openpyxl import load_workbook
|
|
102
|
+
|
|
103
|
+
from .errors import SyncError
|
|
104
|
+
from .valuefmt import display_cell, formula_result
|
|
105
|
+
|
|
106
|
+
own_wb = wb is None
|
|
107
|
+
if own_wb:
|
|
108
|
+
wb = load_workbook(str(xlsx_path))
|
|
109
|
+
if VALUES_SHEET not in wb.sheetnames:
|
|
110
|
+
if own_wb:
|
|
111
|
+
wb.close()
|
|
112
|
+
return PlaceholderValues(set())
|
|
113
|
+
if resolve_formulas and cached_wb is None:
|
|
114
|
+
cached_wb = load_workbook(str(xlsx_path), data_only=True)
|
|
115
|
+
ws = wb[VALUES_SHEET]
|
|
116
|
+
cached_ws = cached_wb[VALUES_SHEET] if cached_wb is not None else None
|
|
117
|
+
values = PlaceholderValues(set())
|
|
118
|
+
seen_rows: dict[str, int] = {}
|
|
119
|
+
for row in range(2, (ws.max_row or 1) + 1):
|
|
120
|
+
field = str(ws.cell(row, 1).value or "").strip()
|
|
121
|
+
if not field:
|
|
122
|
+
continue
|
|
123
|
+
if field in seen_rows:
|
|
124
|
+
raise SyncError(
|
|
125
|
+
f"「{VALUES_SHEET}」字段“{field}”重复出现在第 {seen_rows[field]} 行和第 {row} 行,"
|
|
126
|
+
"无法确定使用哪个值。请合并为一行后再同步。"
|
|
127
|
+
)
|
|
128
|
+
seen_rows[field] = row
|
|
129
|
+
cell = ws.cell(row, 2)
|
|
130
|
+
raw = cell.value
|
|
131
|
+
if resolve_formulas and isinstance(raw, str) and raw.startswith("="):
|
|
132
|
+
raw = formula_result(ws, row, 2, cached_ws)
|
|
133
|
+
if raw is None:
|
|
134
|
+
raise SyncError(
|
|
135
|
+
f"「{VALUES_SHEET}」{cell.coordinate} 是公式但没有可用的计算结果。"
|
|
136
|
+
"请先在 Excel 中打开该工作簿,完成重算并保存后再同步。"
|
|
137
|
+
)
|
|
138
|
+
if field:
|
|
139
|
+
if not resolve_formulas and isinstance(raw, str) and raw.startswith("="):
|
|
140
|
+
values[field] = raw
|
|
141
|
+
else:
|
|
142
|
+
values[field] = display_cell(cell, raw, zero_mode=zero_mode)
|
|
143
|
+
if raw is not None and not (isinstance(raw, str) and not raw.strip()):
|
|
144
|
+
values.filled_fields.add(field)
|
|
145
|
+
return values
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def init_placeholder_sheet(wb):
|
|
149
|
+
"""在工作簿对象中新建「正文信息」骨架表(表头/列宽),返回工作表。"""
|
|
150
|
+
from openpyxl.styles import Font
|
|
151
|
+
|
|
152
|
+
from .config import FONT_NAME, FONT_SIZE
|
|
153
|
+
|
|
154
|
+
ws = wb.create_sheet(VALUES_SHEET)
|
|
155
|
+
ws.cell(1, 1, "字段")
|
|
156
|
+
ws.cell(1, 2, "值")
|
|
157
|
+
ws.cell(1, 3, "来源")
|
|
158
|
+
for c in (1, 2, 3):
|
|
159
|
+
ws.cell(1, c).font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True)
|
|
160
|
+
ws.column_dimensions["A"].width = 24
|
|
161
|
+
ws.column_dimensions["B"].width = 48
|
|
162
|
+
ws.column_dimensions["C"].width = 10
|
|
163
|
+
return ws
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def append_placeholder_sheet(wb, fields: list[str], *, source: str = "全量") -> list[str]:
|
|
167
|
+
"""在工作簿末尾追加缺失字段,不改既有行。"""
|
|
168
|
+
from openpyxl.styles import Font
|
|
169
|
+
from .config import FONT_NAME, FONT_SIZE
|
|
170
|
+
|
|
171
|
+
created = VALUES_SHEET not in wb.sheetnames
|
|
172
|
+
ws = init_placeholder_sheet(wb) if created else wb[VALUES_SHEET]
|
|
173
|
+
if not created and not ws.cell(1, 3).value:
|
|
174
|
+
ws.cell(1, 3, "来源")
|
|
175
|
+
ws.cell(1, 3).font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True)
|
|
176
|
+
ws.column_dimensions["C"].width = 10
|
|
177
|
+
existing = {str(ws.cell(r, 1).value or "").strip() for r in range(2, (ws.max_row or 1) + 1)}
|
|
178
|
+
added = []
|
|
179
|
+
for field in fields:
|
|
180
|
+
if field not in existing:
|
|
181
|
+
ws.append([field, "", source])
|
|
182
|
+
existing.add(field)
|
|
183
|
+
added.append(field)
|
|
184
|
+
return added
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def write_placeholder_sheet(xlsx_path, fields: list[str], *, source: str = "全量", backup: bool = True) -> list[str]:
|
|
188
|
+
"""给工作簿生成/补齐「正文信息」填写骨架,保留已填值;返回新增字段。"""
|
|
189
|
+
from .fsops import check_file_free, load_workbook_for_save, save_docx_xlsx_transaction
|
|
190
|
+
|
|
191
|
+
check_file_free(xlsx_path, False)
|
|
192
|
+
wb = load_workbook_for_save(xlsx_path)
|
|
193
|
+
created = VALUES_SHEET not in wb.sheetnames
|
|
194
|
+
added = append_placeholder_sheet(wb, fields, source=source)
|
|
195
|
+
if added or created:
|
|
196
|
+
save_docx_xlsx_transaction(xlsx_path=xlsx_path, wb=wb, backup=backup)
|
|
197
|
+
wb.close()
|
|
198
|
+
if getattr(wb, "vba_archive", None):
|
|
199
|
+
wb.vba_archive.close()
|
|
200
|
+
return added
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""行结构同步:表头/合计行识别、按 Excel 行数增行删行,并返回被删行的首列文本。"""
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
from docx.oxml.ns import qn
|
|
5
|
+
from .docx_grid import cell_text
|
|
6
|
+
from .errors import SyncError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def first_cell_text(tr) -> str:
|
|
10
|
+
tc = tr.find(qn("w:tc"))
|
|
11
|
+
return cell_text(tc) if tc is not None else ""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def leading_header_count(trs) -> int:
|
|
15
|
+
count = 0
|
|
16
|
+
for tr in trs:
|
|
17
|
+
trPr = tr.find(qn("w:trPr"))
|
|
18
|
+
if trPr is not None and trPr.find(qn("w:tblHeader")) is not None:
|
|
19
|
+
count += 1
|
|
20
|
+
else:
|
|
21
|
+
break
|
|
22
|
+
return count
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def split_rows(trs):
|
|
26
|
+
header = leading_header_count(trs)
|
|
27
|
+
head_rows = trs[:header]
|
|
28
|
+
rest = trs[header:]
|
|
29
|
+
total_index = None
|
|
30
|
+
for idx, tr in enumerate(rest):
|
|
31
|
+
if first_cell_text(tr).strip().startswith("合计"):
|
|
32
|
+
total_index = idx
|
|
33
|
+
break
|
|
34
|
+
if total_index is None:
|
|
35
|
+
return head_rows, list(rest), []
|
|
36
|
+
return head_rows, list(rest[:total_index]), list(rest[total_index:])
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def align_rows(tbl, target_total_rows: int) -> tuple[int, list[str]]:
|
|
40
|
+
"""让数据区行数对齐 Excel。返回 (增删行数, 被删除行的首列文本)。"""
|
|
41
|
+
trs = tbl.findall(qn("w:tr"))
|
|
42
|
+
head_rows, body_rows, total_rows = split_rows(trs)
|
|
43
|
+
target_body = target_total_rows - len(head_rows) - len(total_rows)
|
|
44
|
+
if target_body < 0:
|
|
45
|
+
raise SyncError(f"Excel 中的行数({target_total_rows})少于 Word 表头行数与合计行数之和,无法对齐")
|
|
46
|
+
delta = target_body - len(body_rows)
|
|
47
|
+
if delta == 0:
|
|
48
|
+
return 0, []
|
|
49
|
+
if delta > 0:
|
|
50
|
+
if not body_rows:
|
|
51
|
+
raise SyncError("Word 表格没有可用于复制格式的数据行,无法新增行,请手工调整")
|
|
52
|
+
template = body_rows[-1]
|
|
53
|
+
if template.findall(f".//{qn('w:vMerge')}"):
|
|
54
|
+
raise SyncError("模板数据行含纵向合并单元格,自动增行不安全,请手工在 Word 中调整后重试")
|
|
55
|
+
anchor_node = total_rows[0] if total_rows else body_rows[-1]
|
|
56
|
+
for _ in range(delta):
|
|
57
|
+
clone = copy.deepcopy(template)
|
|
58
|
+
anchor_node.addprevious(clone)
|
|
59
|
+
return delta, []
|
|
60
|
+
deleted: list[str] = []
|
|
61
|
+
for _ in range(-delta):
|
|
62
|
+
if not body_rows:
|
|
63
|
+
raise SyncError("Excel 中删除了过多数据行,Word 表格已无对应行可删,请手工调整")
|
|
64
|
+
row = body_rows.pop()
|
|
65
|
+
deleted.append((first_cell_text(row).strip() or "(空行)").replace("\n", " "))
|
|
66
|
+
row.getparent().remove(row)
|
|
67
|
+
return delta, deleted
|