audit-e2w 0.0.0-stage → 1.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +147 -2
- package/cordis.patch.yml +3 -0
- package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
- package/dsh_plugins/audit-e2w/lib/index.js +114 -0
- package/dsh_plugins/audit-e2w/lib/skill.js +41 -0
- package/excel_word/README.md +380 -0
- package/excel_word/qoder_engine.py +438 -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/align.py +154 -0
- package/excel_word/wesync/api.py +840 -0
- package/excel_word/wesync/backup_history.py +65 -0
- package/excel_word/wesync/changelog.py +58 -0
- package/excel_word/wesync/cli.py +173 -0
- package/excel_word/wesync/commands/__init__.py +8 -0
- package/excel_word/wesync/commands/blank_cmd.py +250 -0
- package/excel_word/wesync/commands/bookmark_cmd.py +115 -0
- package/excel_word/wesync/commands/clear_cmd.py +48 -0
- package/excel_word/wesync/commands/export_cmd.py +220 -0
- package/excel_word/wesync/commands/marks_cmd.py +152 -0
- package/excel_word/wesync/commands/placeholders_cmd.py +87 -0
- package/excel_word/wesync/commands/writeback_cmd.py +513 -0
- package/excel_word/wesync/config.py +96 -0
- package/excel_word/wesync/console.py +78 -0
- package/excel_word/wesync/docx_blank.py +156 -0
- package/excel_word/wesync/docx_bookmarks.py +287 -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 +291 -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 +161 -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 +543 -0
- package/excel_word/wesync/excel_export.py +136 -0
- package/excel_word/wesync/excel_marks.py +193 -0
- package/excel_word/wesync/excel_totals.py +53 -0
- package/excel_word/wesync/fsops.py +214 -0
- package/excel_word/wesync/gui/__init__.py +34 -0
- package/excel_word/wesync/gui/__main__.py +6 -0
- package/excel_word/wesync/gui/app.py +399 -0
- package/excel_word/wesync/gui/manual.py +68 -0
- package/excel_word/wesync/gui/pages/__init__.py +31 -0
- package/excel_word/wesync/gui/pages/_page.py +89 -0
- package/excel_word/wesync/gui/pages/batch_page.py +423 -0
- package/excel_word/wesync/gui/pages/blank_page.py +465 -0
- package/excel_word/wesync/gui/pages/bookmark_page.py +37 -0
- package/excel_word/wesync/gui/pages/export_page.py +88 -0
- package/excel_word/wesync/gui/pages/format_page.py +429 -0
- package/excel_word/wesync/gui/pages/help_page.py +92 -0
- package/excel_word/wesync/gui/pages/history_page.py +145 -0
- package/excel_word/wesync/gui/pages/marks_page.py +178 -0
- package/excel_word/wesync/gui/pages/writeback_page.py +452 -0
- package/excel_word/wesync/gui/resources.py +22 -0
- package/excel_word/wesync/gui/runner.py +74 -0
- package/excel_word/wesync/gui/store.py +34 -0
- package/excel_word/wesync/gui/theme.py +100 -0
- package/excel_word/wesync/gui/widgets/__init__.py +8 -0
- package/excel_word/wesync/gui/widgets/cards.py +20 -0
- package/excel_word/wesync/gui/widgets/filebar.py +58 -0
- package/excel_word/wesync/gui/widgets/logpane.py +110 -0
- package/excel_word/wesync/gui/widgets/nav.py +39 -0
- package/excel_word/wesync/report_format.py +1577 -0
- package/excel_word/wesync/sort_rules.py +244 -0
- package/excel_word/wesync/valuefmt.py +462 -0
- package/package.json +49 -4
- package/qoder_plugins/audit-toolbox/README.md +156 -0
- package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Word 文档语义层:标题层级(outlineLvl/样式)、表名与章节识别、表块信息汇总、同名表去重。"""
|
|
2
|
+
|
|
3
|
+
from docx.oxml.ns import qn
|
|
4
|
+
|
|
5
|
+
from .config import BOOKMARK_PREFIX, DATE_RE, EXCEL_LINK_TEXT
|
|
6
|
+
from .docx_bookmarks import bookmark_starts_in, first_bookmark_in_table
|
|
7
|
+
from .docx_grid import build_cellmap, compute_merges, header_rows, para_text, table_borders, text_grid
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def clean_paragraph_text(text: str) -> str:
|
|
11
|
+
text = text.replace(EXCEL_LINK_TEXT, "")
|
|
12
|
+
return text.strip()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def style_name_of(paragraph) -> str:
|
|
16
|
+
try:
|
|
17
|
+
return paragraph.style.name or ""
|
|
18
|
+
except Exception:
|
|
19
|
+
return ""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def is_heading_style(name: str) -> bool:
|
|
23
|
+
return ("标题" in name) or ("Heading" in name) or name.lower().startswith("heading")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def paragraph_outline_level(p_el) -> int | None:
|
|
27
|
+
"""审计软件生成的文档常直接用 w:outlineLvl 标记标题层级。"""
|
|
28
|
+
pPr = p_el.find(qn("w:pPr"))
|
|
29
|
+
if pPr is None:
|
|
30
|
+
return None
|
|
31
|
+
lvl = pPr.find(qn("w:outlineLvl"))
|
|
32
|
+
if lvl is None:
|
|
33
|
+
return None
|
|
34
|
+
value = lvl.get(qn("w:val"))
|
|
35
|
+
if value is not None and value.lstrip("-").isdigit():
|
|
36
|
+
return int(value)
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def is_heading_paragraph(p) -> bool:
|
|
41
|
+
return paragraph_outline_level(p._p) is not None or is_heading_style(style_name_of(p))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def heading_level(p) -> int | None:
|
|
45
|
+
"""标题层级;仅样式标为标题时按最低优先级处理。"""
|
|
46
|
+
level = paragraph_outline_level(p._p)
|
|
47
|
+
if level is not None:
|
|
48
|
+
return level
|
|
49
|
+
if is_heading_style(style_name_of(p)):
|
|
50
|
+
return 99
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def table_context(doc, items, table_index: int) -> tuple[object, str, str, str]:
|
|
55
|
+
"""返回 (书签锚点段落, 表名, 章节名, 日期提示)。"""
|
|
56
|
+
paragraphs_before = []
|
|
57
|
+
seen_tables = 0
|
|
58
|
+
for kind, obj in items:
|
|
59
|
+
if kind == "tbl":
|
|
60
|
+
if seen_tables == table_index:
|
|
61
|
+
break
|
|
62
|
+
seen_tables += 1
|
|
63
|
+
elif kind == "p":
|
|
64
|
+
paragraphs_before.append(obj)
|
|
65
|
+
|
|
66
|
+
name = ""
|
|
67
|
+
name_index = None
|
|
68
|
+
for idx in range(len(paragraphs_before) - 1, -1, -1):
|
|
69
|
+
text = clean_paragraph_text(para_text(paragraphs_before[idx]._p))
|
|
70
|
+
if text == "" or DATE_RE.match(text):
|
|
71
|
+
continue
|
|
72
|
+
name = text
|
|
73
|
+
name_index = idx
|
|
74
|
+
break
|
|
75
|
+
|
|
76
|
+
# 书签与“回到 Excel”链接锚定在表格前最近的非空段落(多为表格标题行或日期行),
|
|
77
|
+
# 这样每张表各有一个独占锚点,避免同一段落被多张表共用。
|
|
78
|
+
anchor = None
|
|
79
|
+
for p in reversed(paragraphs_before):
|
|
80
|
+
if clean_paragraph_text(para_text(p._p)) != "":
|
|
81
|
+
anchor = p
|
|
82
|
+
break
|
|
83
|
+
|
|
84
|
+
# 章节取“层级高于表名所在标题”的最近标题,找不到时退化为最近的标题段落。
|
|
85
|
+
name_level = paragraph_outline_level(paragraphs_before[name_index]._p) if name_index is not None else None
|
|
86
|
+
section = ""
|
|
87
|
+
start = (name_index - 1) if name_index is not None else (len(paragraphs_before) - 1)
|
|
88
|
+
nearest_heading = ""
|
|
89
|
+
for idx in range(start, -1, -1):
|
|
90
|
+
p = paragraphs_before[idx]
|
|
91
|
+
text = clean_paragraph_text(para_text(p._p))
|
|
92
|
+
if text == "" or DATE_RE.match(text):
|
|
93
|
+
continue
|
|
94
|
+
level = heading_level(p)
|
|
95
|
+
if level is None:
|
|
96
|
+
continue
|
|
97
|
+
if not nearest_heading:
|
|
98
|
+
nearest_heading = text
|
|
99
|
+
if name_level is not None and level < name_level:
|
|
100
|
+
section = text
|
|
101
|
+
break
|
|
102
|
+
if not section:
|
|
103
|
+
section = nearest_heading
|
|
104
|
+
|
|
105
|
+
date_hint = ""
|
|
106
|
+
for p in reversed(paragraphs_before):
|
|
107
|
+
text = clean_paragraph_text(para_text(p._p))
|
|
108
|
+
if DATE_RE.match(text):
|
|
109
|
+
date_hint = text
|
|
110
|
+
break
|
|
111
|
+
return anchor, name, section, date_hint
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def collect_table_info(doc, items, index: int, tab) -> dict:
|
|
115
|
+
tbl = tab._tbl
|
|
116
|
+
trs, cellmap, ncols = build_cellmap(tbl)
|
|
117
|
+
merges = compute_merges(cellmap)
|
|
118
|
+
borders = table_borders(tbl)
|
|
119
|
+
grid = text_grid(tbl, cellmap)
|
|
120
|
+
anchors, name, section, date_hint = table_context(doc, items, index)
|
|
121
|
+
code = f"T{index + 1:02d}"
|
|
122
|
+
# 锚点段落上已有的书签(导出/书签命令会据此复用;这里不做臆测命名)
|
|
123
|
+
anchor_names = bookmark_starts_in(anchors._p) if anchors is not None else []
|
|
124
|
+
own_bookmark = next((n for n in anchor_names if n.startswith(BOOKMARK_PREFIX)), "")
|
|
125
|
+
return {
|
|
126
|
+
"index": index,
|
|
127
|
+
"code": code,
|
|
128
|
+
"tbl": tbl,
|
|
129
|
+
"nrows": len(trs),
|
|
130
|
+
"ncols": ncols,
|
|
131
|
+
"cellmap": cellmap,
|
|
132
|
+
"text": grid,
|
|
133
|
+
"merges": merges,
|
|
134
|
+
"borders": borders,
|
|
135
|
+
"header_rows": header_rows(trs),
|
|
136
|
+
"bookmark": own_bookmark,
|
|
137
|
+
"old_bookmark": first_bookmark_in_table(tbl),
|
|
138
|
+
"name": name or f"表{index + 1}",
|
|
139
|
+
"section": section or "(未识别章节)",
|
|
140
|
+
"date_hint": date_hint,
|
|
141
|
+
"anchor_p": anchors._p if anchors is not None else None,
|
|
142
|
+
"anchor_paragraph": anchors,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def dedupe_table_names(infos: list[dict]) -> None:
|
|
147
|
+
"""同章节下多张表名称重复时,用日期或表号区分,便于在 Excel 中辨认。"""
|
|
148
|
+
seen: set[str] = set()
|
|
149
|
+
for info in infos:
|
|
150
|
+
name = info["name"]
|
|
151
|
+
if name in seen:
|
|
152
|
+
hint = info["date_hint"]
|
|
153
|
+
candidate = f"{name}({hint})" if hint else f"{name}(表{info['index'] + 1})"
|
|
154
|
+
if candidate in seen:
|
|
155
|
+
candidate = f"{name}(表{info['index'] + 1})"
|
|
156
|
+
info["name"] = candidate
|
|
157
|
+
seen.add(info["name"])
|
|
@@ -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,161 @@
|
|
|
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
|
+
def _iter_paragraphs(doc):
|
|
16
|
+
"""正文段落(含表格内)+ 各节页眉页脚(含其中表格)。"""
|
|
17
|
+
def _walk(container):
|
|
18
|
+
yield from container.paragraphs
|
|
19
|
+
for table in container.tables:
|
|
20
|
+
for row in table.rows:
|
|
21
|
+
for cell in row.cells:
|
|
22
|
+
yield from _walk(cell)
|
|
23
|
+
|
|
24
|
+
yield from _walk(doc)
|
|
25
|
+
for section in doc.sections:
|
|
26
|
+
for part in (section.header, section.footer,
|
|
27
|
+
section.first_page_header, section.first_page_footer,
|
|
28
|
+
section.even_page_header, section.even_page_footer):
|
|
29
|
+
if part is not None:
|
|
30
|
+
yield from _walk(part)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def scan_placeholders(doc) -> list[str]:
|
|
34
|
+
"""按出现顺序去重列出全部占位符字段名。"""
|
|
35
|
+
seen: dict[str, None] = {}
|
|
36
|
+
for p in _iter_paragraphs(doc):
|
|
37
|
+
for m in PLACEHOLDER_RE.finditer(p.text):
|
|
38
|
+
field = m.group(1).strip()
|
|
39
|
+
if field:
|
|
40
|
+
seen.setdefault(field, None)
|
|
41
|
+
return list(seen)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _replace_in_paragraph(p, values: dict[str, str]) -> list[tuple[str, str]]:
|
|
45
|
+
runs = p.runs
|
|
46
|
+
if not runs:
|
|
47
|
+
return []
|
|
48
|
+
full = "".join(r.text for r in runs)
|
|
49
|
+
matches = [m for m in PLACEHOLDER_RE.finditer(full) if m.group(1).strip() in values]
|
|
50
|
+
if not matches:
|
|
51
|
+
return []
|
|
52
|
+
spans = []
|
|
53
|
+
pos = 0
|
|
54
|
+
for r in runs:
|
|
55
|
+
spans.append((pos, pos + len(r.text)))
|
|
56
|
+
pos += len(r.text)
|
|
57
|
+
done = []
|
|
58
|
+
for m in reversed(matches): # 从右往左改,前面的偏移不受影响
|
|
59
|
+
field = m.group(1).strip()
|
|
60
|
+
replacement = values[field]
|
|
61
|
+
s, e = m.span()
|
|
62
|
+
first = True
|
|
63
|
+
for r, (rs, re_) in zip(runs, spans):
|
|
64
|
+
if re_ <= s or rs >= e:
|
|
65
|
+
continue
|
|
66
|
+
head = r.text[: max(0, s - rs)] if first else ""
|
|
67
|
+
tail = r.text[max(0, min(len(r.text), e - rs)):]
|
|
68
|
+
r.text = head + (replacement if first else "") + tail
|
|
69
|
+
first = False
|
|
70
|
+
done.append((field, replacement))
|
|
71
|
+
return list(reversed(done))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def apply_placeholders(doc, values: dict[str, str], *, dry_run: bool = False) -> dict:
|
|
75
|
+
"""返回 {"replaced": [(字段, 新值)], "missing": [字段]};dry_run 只列计划不改文档。"""
|
|
76
|
+
fields = scan_placeholders(doc)
|
|
77
|
+
missing = [f for f in fields if not str(values.get(f, "")).strip()]
|
|
78
|
+
if dry_run:
|
|
79
|
+
return {"replaced": [(f, str(values[f])) for f in fields if f not in missing], "missing": missing}
|
|
80
|
+
replaced = []
|
|
81
|
+
effective = {f: str(values[f]) for f in fields if f not in missing}
|
|
82
|
+
for p in _iter_paragraphs(doc):
|
|
83
|
+
replaced.extend(_replace_in_paragraph(p, effective))
|
|
84
|
+
return {"replaced": replaced, "missing": missing}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def read_placeholder_values(xlsx_path, *, resolve_formulas: bool = True) -> dict[str, str]:
|
|
88
|
+
"""读工作簿「正文信息」表(A=字段 B=值,首行表头);无该表返回空。
|
|
89
|
+
|
|
90
|
+
值按单元格在 Excel 里的显示效果转换(与表格回写同口径):日期用其数字格式渲染
|
|
91
|
+
(如 2026-12-31、2026年12月31日),不会出现 "2026-12-31 00:00:00" 这类原始值。
|
|
92
|
+
公式优先取 Excel 缓存结果,其次轻量求值;导出保留旧值时可按原公式保留。
|
|
93
|
+
"""
|
|
94
|
+
from openpyxl import load_workbook
|
|
95
|
+
|
|
96
|
+
from .errors import SyncError
|
|
97
|
+
from .valuefmt import display_cell, formula_result
|
|
98
|
+
|
|
99
|
+
wb = load_workbook(str(xlsx_path))
|
|
100
|
+
if VALUES_SHEET not in wb.sheetnames:
|
|
101
|
+
return {}
|
|
102
|
+
cached_wb = load_workbook(str(xlsx_path), data_only=True) if resolve_formulas else None
|
|
103
|
+
ws = wb[VALUES_SHEET]
|
|
104
|
+
cached_ws = cached_wb[VALUES_SHEET] if cached_wb is not None else None
|
|
105
|
+
values = {}
|
|
106
|
+
for row in range(2, (ws.max_row or 1) + 1):
|
|
107
|
+
field = str(ws.cell(row, 1).value or "").strip()
|
|
108
|
+
cell = ws.cell(row, 2)
|
|
109
|
+
raw = cell.value
|
|
110
|
+
if resolve_formulas and isinstance(raw, str) and raw.startswith("="):
|
|
111
|
+
raw = formula_result(ws, row, 2, cached_ws)
|
|
112
|
+
if raw is None:
|
|
113
|
+
raise SyncError(
|
|
114
|
+
f"「{VALUES_SHEET}」{cell.coordinate} 是公式但没有可用的计算结果。"
|
|
115
|
+
"请先在 Excel 中打开该工作簿,完成重算并保存后再同步。"
|
|
116
|
+
)
|
|
117
|
+
if field:
|
|
118
|
+
if not resolve_formulas and isinstance(raw, str) and raw.startswith("="):
|
|
119
|
+
values[field] = raw
|
|
120
|
+
else:
|
|
121
|
+
values[field] = display_cell(cell, raw)
|
|
122
|
+
return values
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def init_placeholder_sheet(wb):
|
|
126
|
+
"""在工作簿对象中新建「正文信息」骨架表(表头/列宽),返回工作表。"""
|
|
127
|
+
from openpyxl.styles import Font
|
|
128
|
+
|
|
129
|
+
from .config import FONT_NAME, FONT_SIZE
|
|
130
|
+
|
|
131
|
+
ws = wb.create_sheet(VALUES_SHEET)
|
|
132
|
+
ws.cell(1, 1, "字段")
|
|
133
|
+
ws.cell(1, 2, "值")
|
|
134
|
+
for c in (1, 2):
|
|
135
|
+
ws.cell(1, c).font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True)
|
|
136
|
+
ws.column_dimensions["A"].width = 24
|
|
137
|
+
ws.column_dimensions["B"].width = 48
|
|
138
|
+
return ws
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def write_placeholder_sheet(xlsx_path, fields: list[str]) -> list[str]:
|
|
142
|
+
"""给工作簿生成/补齐「正文信息」填写骨架,保留已填值;返回新增字段。"""
|
|
143
|
+
from .fsops import backup_file, check_file_free, load_workbook_for_save
|
|
144
|
+
|
|
145
|
+
check_file_free(xlsx_path, False)
|
|
146
|
+
wb = load_workbook_for_save(xlsx_path)
|
|
147
|
+
created = VALUES_SHEET not in wb.sheetnames
|
|
148
|
+
ws = init_placeholder_sheet(wb) if created else wb[VALUES_SHEET]
|
|
149
|
+
existing = {str(ws.cell(r, 1).value or "").strip() for r in range(2, (ws.max_row or 1) + 1)}
|
|
150
|
+
added = []
|
|
151
|
+
for field in fields:
|
|
152
|
+
if field not in existing:
|
|
153
|
+
ws.append([field, ""])
|
|
154
|
+
added.append(field)
|
|
155
|
+
if added or created:
|
|
156
|
+
backup_file(xlsx_path)
|
|
157
|
+
wb.save(str(xlsx_path))
|
|
158
|
+
wb.close()
|
|
159
|
+
if getattr(wb, "vba_archive", None):
|
|
160
|
+
wb.vba_archive.close()
|
|
161
|
+
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
|