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.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -3
  3. package/cordis.patch.yml +3 -0
  4. package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
  5. package/dsh_plugins/audit-e2w/lib/index.js +122 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +42 -0
  7. package/excel_word/README.md +388 -0
  8. package/excel_word/qoder_engine.py +437 -0
  9. package/excel_word/requirements.txt +4 -0
  10. package/excel_word/wesync/__init__.py +19 -0
  11. package/excel_word/wesync/__main__.py +6 -0
  12. package/excel_word/wesync/ai/__init__.py +52 -0
  13. package/excel_word/wesync/ai/actions.py +369 -0
  14. package/excel_word/wesync/ai/client.py +340 -0
  15. package/excel_word/wesync/ai/config.py +291 -0
  16. package/excel_word/wesync/ai/docs.py +177 -0
  17. package/excel_word/wesync/ai/prompts.py +288 -0
  18. package/excel_word/wesync/ai/tasks/__init__.py +26 -0
  19. package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
  20. package/excel_word/wesync/ai/tasks/combined.py +123 -0
  21. package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
  22. package/excel_word/wesync/ai/tasks/headings.py +119 -0
  23. package/excel_word/wesync/ai/tasks/help_task.py +69 -0
  24. package/excel_word/wesync/ai/tasks/roles.py +128 -0
  25. package/excel_word/wesync/align.py +155 -0
  26. package/excel_word/wesync/api.py +1292 -0
  27. package/excel_word/wesync/backup_history.py +100 -0
  28. package/excel_word/wesync/changelog.py +58 -0
  29. package/excel_word/wesync/cli.py +191 -0
  30. package/excel_word/wesync/commands/__init__.py +8 -0
  31. package/excel_word/wesync/commands/blank_cmd.py +279 -0
  32. package/excel_word/wesync/commands/bookmark_cmd.py +146 -0
  33. package/excel_word/wesync/commands/clear_cmd.py +50 -0
  34. package/excel_word/wesync/commands/export_cmd.py +270 -0
  35. package/excel_word/wesync/commands/incremental_cmd.py +157 -0
  36. package/excel_word/wesync/commands/marks_cmd.py +160 -0
  37. package/excel_word/wesync/commands/placeholders_cmd.py +92 -0
  38. package/excel_word/wesync/commands/writeback_cmd.py +469 -0
  39. package/excel_word/wesync/config.py +97 -0
  40. package/excel_word/wesync/console.py +85 -0
  41. package/excel_word/wesync/docx_blank.py +156 -0
  42. package/excel_word/wesync/docx_bookmarks.py +294 -0
  43. package/excel_word/wesync/docx_columns.py +257 -0
  44. package/excel_word/wesync/docx_edit.py +77 -0
  45. package/excel_word/wesync/docx_grid.py +212 -0
  46. package/excel_word/wesync/docx_marks.py +399 -0
  47. package/excel_word/wesync/docx_meta.py +157 -0
  48. package/excel_word/wesync/docx_newtable.py +220 -0
  49. package/excel_word/wesync/docx_placeholders.py +200 -0
  50. package/excel_word/wesync/docx_rows.py +67 -0
  51. package/excel_word/wesync/errors.py +5 -0
  52. package/excel_word/wesync/excel_blocks.py +502 -0
  53. package/excel_word/wesync/excel_export.py +143 -0
  54. package/excel_word/wesync/excel_marks.py +265 -0
  55. package/excel_word/wesync/excel_totals.py +53 -0
  56. package/excel_word/wesync/fsops.py +219 -0
  57. package/excel_word/wesync/gui/__init__.py +53 -0
  58. package/excel_word/wesync/gui/__main__.py +6 -0
  59. package/excel_word/wesync/gui/app.py +613 -0
  60. package/excel_word/wesync/gui/manual.py +70 -0
  61. package/excel_word/wesync/gui/pages/__init__.py +80 -0
  62. package/excel_word/wesync/gui/pages/_page.py +211 -0
  63. package/excel_word/wesync/gui/pages/ai_page.py +854 -0
  64. package/excel_word/wesync/gui/pages/batch_page.py +456 -0
  65. package/excel_word/wesync/gui/pages/blank_page.py +530 -0
  66. package/excel_word/wesync/gui/pages/bookmark_page.py +97 -0
  67. package/excel_word/wesync/gui/pages/export_page.py +141 -0
  68. package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
  69. package/excel_word/wesync/gui/pages/format_page.py +551 -0
  70. package/excel_word/wesync/gui/pages/help_page.py +158 -0
  71. package/excel_word/wesync/gui/pages/history_page.py +168 -0
  72. package/excel_word/wesync/gui/pages/marks_page.py +211 -0
  73. package/excel_word/wesync/gui/pages/settings_page.py +450 -0
  74. package/excel_word/wesync/gui/pages/writeback_page.py +473 -0
  75. package/excel_word/wesync/gui/resources.py +22 -0
  76. package/excel_word/wesync/gui/runner.py +90 -0
  77. package/excel_word/wesync/gui/store.py +50 -0
  78. package/excel_word/wesync/gui/theme.py +271 -0
  79. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  80. package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
  81. package/excel_word/wesync/gui/widgets/cards.py +139 -0
  82. package/excel_word/wesync/gui/widgets/chips.py +565 -0
  83. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  84. package/excel_word/wesync/gui/widgets/logpane.py +126 -0
  85. package/excel_word/wesync/gui/widgets/nav.py +294 -0
  86. package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
  87. package/excel_word/wesync/report_format.py +1585 -0
  88. package/excel_word/wesync/settings.py +35 -0
  89. package/excel_word/wesync/sort_rules.py +293 -0
  90. package/excel_word/wesync/valuefmt.py +485 -0
  91. package/package.json +53 -6
  92. package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
  93. package/qoder_plugins/audit-toolbox/README.md +159 -0
  94. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,257 @@
1
+ """列结构同步:用表头文本打分定位列、在 Word 中插入/删除列并同步合并区,空白新增列按表忽略。"""
2
+
3
+ import copy
4
+ import itertools
5
+ from docx.oxml import OxmlElement
6
+ from docx.oxml.ns import qn
7
+ from .config import MAX_COLUMN_SHIFT, SKIP_COLUMN
8
+ from .console import log
9
+ from .docx_edit import _remove_text_nodes
10
+ from .docx_grid import build_cellmap, cell_text, header_rows, parse_tc_props
11
+ from .errors import SyncError
12
+ from .valuefmt import display_cell
13
+
14
+
15
+ def _set_grid_span(tc, span: int) -> None:
16
+ tcPr = tc.find(qn("w:tcPr"))
17
+ if tcPr is None:
18
+ tcPr = OxmlElement("w:tcPr")
19
+ tc.insert(0, tcPr)
20
+ node = tcPr.find(qn("w:gridSpan"))
21
+ if span <= 1:
22
+ if node is not None:
23
+ tcPr.remove(node)
24
+ return
25
+ if node is None:
26
+ node = OxmlElement("w:gridSpan")
27
+ tcPr.append(node)
28
+ node.set(qn("w:val"), str(span))
29
+
30
+
31
+ def _clone_empty_tc(tc):
32
+ """克隆单元格格式(宽度/边框/对齐)并清空内容,作为新列的单元格。"""
33
+ new_tc = copy.deepcopy(tc)
34
+ tcPr = new_tc.find(qn("w:tcPr"))
35
+ if tcPr is not None:
36
+ for tag in ("w:vMerge", "w:gridSpan"):
37
+ node = tcPr.find(qn(tag))
38
+ if node is not None:
39
+ tcPr.remove(node)
40
+ for node in list(new_tc.iter(qn("w:bookmarkStart"))) + list(new_tc.iter(qn("w:bookmarkEnd"))):
41
+ parent = node.getparent()
42
+ if parent is not None:
43
+ parent.remove(node)
44
+ paragraphs = new_tc.findall(qn("w:p"))
45
+ for extra in paragraphs[1:]:
46
+ new_tc.remove(extra)
47
+ if paragraphs:
48
+ _remove_text_nodes(paragraphs[0])
49
+ else:
50
+ new_tc.append(OxmlElement("w:p"))
51
+ return new_tc
52
+
53
+
54
+ def _insert_tc_at(tr, pos: int) -> None:
55
+ col = 0
56
+ prev = None
57
+ for tc in tr.findall(qn("w:tc")):
58
+ span, _ = parse_tc_props(tc)
59
+ if col < pos < col + span:
60
+ _set_grid_span(tc, span + 1) # 插入点落在横向合并区内部:扩展合并
61
+ return
62
+ if col == pos:
63
+ tc.addprevious(_clone_empty_tc(tc))
64
+ return
65
+ prev = tc
66
+ col += span
67
+ if prev is None:
68
+ raise SyncError("表格行内没有可复制的单元格,无法插入列")
69
+ prev.addnext(_clone_empty_tc(prev))
70
+
71
+
72
+ def insert_word_column(tbl, pos: int) -> None:
73
+ grid = tbl.find(qn("w:tblGrid"))
74
+ if grid is not None:
75
+ cols = grid.findall(qn("w:gridCol"))
76
+ if cols:
77
+ source = cols[pos - 1] if 0 < pos <= len(cols) else cols[0]
78
+ new_col = copy.deepcopy(source)
79
+ if pos < len(cols):
80
+ cols[pos].addprevious(new_col)
81
+ else:
82
+ cols[-1].addnext(new_col)
83
+ for tr in tbl.findall(qn("w:tr")):
84
+ _insert_tc_at(tr, pos)
85
+
86
+
87
+ def delete_word_column(tbl, pos: int) -> None:
88
+ grid = tbl.find(qn("w:tblGrid"))
89
+ if grid is not None:
90
+ cols = grid.findall(qn("w:gridCol"))
91
+ if len(cols) <= 1:
92
+ raise SyncError("表格只剩一列,无法再删除")
93
+ if pos < len(cols):
94
+ grid.remove(cols[pos])
95
+ for tr in tbl.findall(qn("w:tr")):
96
+ col = 0
97
+ for tc in tr.findall(qn("w:tc")):
98
+ span, _ = parse_tc_props(tc)
99
+ if col <= pos < col + span:
100
+ if span > 1:
101
+ _set_grid_span(tc, span - 1)
102
+ else:
103
+ tr.remove(tc)
104
+ break
105
+ col += span
106
+
107
+
108
+ def _excel_cell_display(ws, row: int, col: int, cached=None) -> str:
109
+ cell = ws.cell(row, col)
110
+ value = cell.value
111
+ if isinstance(value, str) and value.startswith("=") and cached is not None:
112
+ value = cached.get((ws.title, row, col))
113
+ return display_cell(cell, value).strip()
114
+
115
+
116
+ def _word_column_signatures(trs, cellmap, ncols: int) -> list[tuple[str, ...]]:
117
+ header_idx = sorted(header_rows(trs)) or list(range(min(2, len(trs))))
118
+ signatures = []
119
+ for col in range(ncols):
120
+ texts = []
121
+ for row in header_idx:
122
+ if row >= len(cellmap):
123
+ texts.append("")
124
+ continue
125
+ pos = cellmap[row][col]
126
+ texts.append(cell_text(pos.tc).strip() if (pos is not None and pos.owner) else "")
127
+ signatures.append(tuple(texts))
128
+ return signatures
129
+
130
+
131
+ def _excel_column_signatures(ws, grid_rows: list[int], ncols: int, header_count: int, cached=None, col0: int = 2) -> list[tuple[str, ...]]:
132
+ rows = grid_rows[: max(1, header_count)]
133
+ signatures = []
134
+ for col in range(ncols):
135
+ signatures.append(tuple(_excel_cell_display(ws, row, col0 + col, cached) for row in rows))
136
+ return signatures
137
+
138
+
139
+ def _score_mapping(word_sigs, excel_sigs, mapping: list[int | None]) -> tuple[float, int, int]:
140
+ """返回 (匹配得分, 参与比较的列数, 文本真正匹配上的单元格数)。"""
141
+ matched = 0.0
142
+ compared = 0
143
+ non_empty = 0
144
+ for excel_col, word_col in enumerate(mapping):
145
+ if word_col is None or word_col < 0 or word_col >= len(word_sigs):
146
+ continue
147
+ compared += 1
148
+ for word_text, excel_text in zip(word_sigs[word_col], excel_sigs[excel_col]):
149
+ if word_text and excel_text:
150
+ if word_text == excel_text:
151
+ matched += 1.0
152
+ non_empty += 1
153
+ elif not word_text and not excel_text:
154
+ matched += 0.5
155
+ score = matched / compared if compared else 0.0
156
+ return score, compared, non_empty
157
+
158
+
159
+ def _column_is_empty(ws, col: int, grid_rows: list[int], col0: int = 2) -> bool:
160
+ return all(_excel_cell_display(ws, row, col0 + col) == "" for row in grid_rows)
161
+
162
+
163
+ def plan_column_alignment(word_sigs, excel_sigs, word_ncols: int, excel_ncols: int, ws, grid_rows, code: str, col0: int = 2):
164
+ """用表头文本逐列比对,返回 Excel 列映射。
165
+
166
+ 映射值含义:整数 = 对应的旧 Word 列;None = 需要新增的 Word 列;
167
+ SKIP_COLUMN = 该 Excel 列在本表中整列空白,本次忽略(不写入 Word)。
168
+ """
169
+ if excel_ncols == word_ncols:
170
+ return list(range(word_ncols))
171
+ shift = abs(excel_ncols - word_ncols)
172
+ if shift > MAX_COLUMN_SHIFT:
173
+ raise SyncError(
174
+ f"{code}:Excel 与 Word 相差 {shift} 列,超出自动同步范围(最多 {MAX_COLUMN_SHIFT} 列)。"
175
+ f"请重新执行 export,或手工把列结构改回一致后重试"
176
+ )
177
+ best = None
178
+ if excel_ncols > word_ncols:
179
+ for combo in itertools.combinations(range(excel_ncols), shift):
180
+ inserted = set(combo)
181
+ mapping: list[int | None] = []
182
+ word_col = 0
183
+ for excel_col in range(excel_ncols):
184
+ if excel_col in inserted:
185
+ # 有内容的新增列同步到 Word;整列空白的新增列在本表中忽略
186
+ mapping.append(SKIP_COLUMN if _column_is_empty(ws, excel_col, grid_rows, col0) else None)
187
+ else:
188
+ mapping.append(word_col)
189
+ word_col += 1
190
+ score, compared, non_empty = _score_mapping(word_sigs, excel_sigs, mapping)
191
+ skips = sum(1 for value in mapping if value == SKIP_COLUMN)
192
+ inserts = sum(1 for value in mapping if value is None)
193
+ key = (round(score, 6), non_empty, skips, -inserts, -min(inserted))
194
+ if best is None or key > best[0]:
195
+ best = (key, mapping, min(inserted), compared, non_empty)
196
+ else:
197
+ for combo in itertools.combinations(range(word_ncols), shift):
198
+ deleted = set(combo)
199
+ remaining = [col for col in range(word_ncols) if col not in deleted]
200
+ mapping = list(remaining)
201
+ score, compared, non_empty = _score_mapping(word_sigs, excel_sigs, mapping)
202
+ key = (round(score, 6), non_empty, 0, -min(deleted))
203
+ if best is None or key > best[0]:
204
+ best = (key, mapping, min(deleted), compared, non_empty)
205
+ if best is None:
206
+ raise SyncError(f"{code}:无法判断列位置,请重新执行 export 或手工调整列结构")
207
+ score, compared, non_empty = best[0][0], best[3], best[4]
208
+ if compared < 2 or non_empty < 2 or score < 0.8:
209
+ raise SyncError(
210
+ f"{code}:Word 为 {word_ncols} 列、Excel 为 {excel_ncols} 列,表头文本匹配不足"
211
+ f"(得分 {score:.2f}、可比列 {compared}、真实匹配 {non_empty}),"
212
+ f"为避免写错列已跳过该表。请核对书签是否锚定正确,或重新执行 export"
213
+ )
214
+ return best[1]
215
+
216
+
217
+ def sync_columns(tbl, ws, block: dict, code: str, cached=None) -> tuple[list[int], int, int]:
218
+ """按 Excel 列结构同步 Word 表格的列,返回 (有效 Excel 列顺序, 新增列数, 删除列数)。"""
219
+ trs, cellmap, word_ncols = build_cellmap(tbl)
220
+ excel_ncols = block["ncols"]
221
+ if word_ncols == excel_ncols:
222
+ return list(range(excel_ncols)), 0, 0
223
+ word_sigs = _word_column_signatures(trs, cellmap, word_ncols)
224
+ header_count = len(sorted(header_rows(trs))) or min(2, len(trs))
225
+ excel_sigs = _excel_column_signatures(ws, block["grid_rows"], excel_ncols, header_count, cached, block.get("col0", 2))
226
+ mapping = plan_column_alignment(word_sigs, excel_sigs, word_ncols, excel_ncols, ws, block["grid_rows"], code, block.get("col0", 2))
227
+
228
+ inserted = 0
229
+ deleted = 0
230
+ if excel_ncols > word_ncols:
231
+ positions = [col for col, word_col in enumerate(mapping) if word_col is None]
232
+ for pos in sorted(positions, reverse=True):
233
+ insert_word_column(tbl, pos)
234
+ inserted += 1
235
+ skipped = [col for col, word_col in enumerate(mapping) if word_col == SKIP_COLUMN]
236
+ if inserted:
237
+ log(f"[结构] {code}:Word 新增 {inserted} 列(插入于第 {min(positions) + 1} 列起)")
238
+ if skipped:
239
+ log(
240
+ f"[结构] {code}:Excel 第 {'、'.join(str(col + 1) for col in skipped)} 列在本表整列空白,"
241
+ f"已按空白列忽略(填入表头或数据后即可同步到 Word)"
242
+ )
243
+ else:
244
+ used = {col for col in mapping if col is not None and col >= 0}
245
+ positions = [col for col in range(word_ncols) if col not in used]
246
+ for pos in sorted(positions, reverse=True):
247
+ delete_word_column(tbl, pos)
248
+ deleted += 1
249
+ log(f"[结构] {code}:Word 删除 {deleted} 列(第 {min(positions) + 1} 列起)")
250
+
251
+ include = [col for col, word_col in enumerate(mapping) if word_col != SKIP_COLUMN]
252
+ _, _, new_ncols = build_cellmap(tbl)
253
+ if new_ncols != len(include):
254
+ raise SyncError(
255
+ f"{code}:列结构同步后 Word 为 {new_ncols} 列、Excel 有效列为 {len(include)} 列,未对齐"
256
+ )
257
+ return include, inserted, deleted
@@ -0,0 +1,77 @@
1
+ """Word 单元格写入:替换文字但保留 run 格式、段落数量与单元格属性。"""
2
+
3
+ import copy
4
+ from docx.oxml import OxmlElement
5
+ from docx.oxml.ns import qn
6
+ from .docx_grid import cell_text
7
+
8
+
9
+ def _remove_text_nodes(p_el) -> None:
10
+ for t in list(p_el.findall(qn("w:r"))):
11
+ p_el.remove(t)
12
+ for hl in list(p_el.findall(qn("w:hyperlink"))):
13
+ p_el.remove(hl)
14
+
15
+
16
+ def _set_paragraph_text(p_el, text: str, fallback_rpr=None) -> None:
17
+ """写入段落文本,保留第一个 run 的格式。"""
18
+ runs = p_el.findall(qn("w:r"))
19
+ for hl in list(p_el.findall(qn("w:hyperlink"))):
20
+ p_el.remove(hl)
21
+ if runs:
22
+ keep = runs[0]
23
+ for extra in runs[1:]:
24
+ p_el.remove(extra)
25
+ texts = keep.findall(qn("w:t"))
26
+ for idx, node in enumerate(texts):
27
+ if idx == 0:
28
+ node.text = text
29
+ node.set(qn("xml:space"), "preserve")
30
+ else:
31
+ keep.remove(node)
32
+ if not texts:
33
+ node = OxmlElement("w:t")
34
+ node.text = text
35
+ node.set(qn("xml:space"), "preserve")
36
+ keep.append(node)
37
+ return
38
+
39
+ rpr = None
40
+ pPr = p_el.find(qn("w:pPr"))
41
+ if pPr is not None:
42
+ rpr = pPr.find(qn("w:rPr"))
43
+ if rpr is None:
44
+ rpr = fallback_rpr
45
+ run = OxmlElement("w:r")
46
+ if rpr is not None:
47
+ run.append(copy.deepcopy(rpr))
48
+ node = OxmlElement("w:t")
49
+ node.text = text
50
+ node.set(qn("xml:space"), "preserve")
51
+ run.append(node)
52
+ p_el.append(run)
53
+
54
+
55
+ def set_cell_text(tc, text: str, fallback_rpr=None) -> bool:
56
+ """把单元格文本设为 text(\n 表示多段),保留格式。返回是否发生改动。"""
57
+ if tc is None:
58
+ return False
59
+ if cell_text(tc) == text:
60
+ return False
61
+ segments = text.split("\n") if text != "" else [""]
62
+ paras = tc.findall(qn("w:p"))
63
+ if not paras:
64
+ node = OxmlElement("w:p")
65
+ tc.append(node)
66
+ paras = [node]
67
+ while len(paras) > len(segments):
68
+ extra = paras.pop()
69
+ tc.remove(extra)
70
+ while len(paras) < len(segments):
71
+ clone = copy.deepcopy(paras[-1])
72
+ _remove_text_nodes(clone)
73
+ paras[-1].addnext(clone)
74
+ paras = tc.findall(qn("w:p"))
75
+ for p_el, segment in zip(paras, segments):
76
+ _set_paragraph_text(p_el, segment, fallback_rpr)
77
+ return True
@@ -0,0 +1,212 @@
1
+ """Word 表格网格层:解析 tblGrid/gridSpan/vMerge,得到网格坐标、合并区、边框与对齐、单元格文本。"""
2
+
3
+ import copy
4
+ from docx.oxml.ns import qn
5
+ from docx.table import Table
6
+ from docx.text.paragraph import Paragraph
7
+ from .config import BORDER_MAP, JC_MAP, VA_MAP
8
+
9
+
10
+ class GridPos:
11
+ """表格网格中的一个位置。owner=True 表示该位置是单元格的真实起点。"""
12
+
13
+ __slots__ = ("tc", "owner", "vmerge", "span")
14
+
15
+ def __init__(self, tc, owner: bool, vmerge: str | None, span: int = 1):
16
+ self.tc = tc
17
+ self.owner = owner
18
+ self.vmerge = vmerge
19
+ self.span = span
20
+
21
+
22
+ def body_items(doc) -> list[tuple[str, object]]:
23
+ """按文档顺序返回正文中的段落与表格。"""
24
+ items: list[tuple[str, object]] = []
25
+ for child in doc.element.body.iterchildren():
26
+ tag = child.tag.split("}")[1]
27
+ if tag == "p":
28
+ items.append(("p", Paragraph(child, doc)))
29
+ elif tag == "tbl":
30
+ items.append(("tbl", Table(child, doc)))
31
+ return items
32
+
33
+
34
+ def parse_tc_props(tc):
35
+ tcPr = tc.find(qn("w:tcPr"))
36
+ span = 1
37
+ vmerge = None
38
+ if tcPr is not None:
39
+ grid_span = tcPr.find(qn("w:gridSpan"))
40
+ if grid_span is not None:
41
+ try:
42
+ span = max(1, int(grid_span.get(qn("w:val"), "1")))
43
+ except (TypeError, ValueError):
44
+ span = 1
45
+ vm = tcPr.find(qn("w:vMerge"))
46
+ if vm is not None:
47
+ vmerge = "restart" if vm.get(qn("w:val")) == "restart" else "continue"
48
+ return span, vmerge
49
+
50
+
51
+ def build_cellmap(tbl):
52
+ """返回 (trs, cellmap, ncols)。cellmap[r][c] 为 GridPos 或 None。"""
53
+ trs = tbl.findall(qn("w:tr"))
54
+ grid = tbl.find(qn("w:tblGrid"))
55
+ ncols = len(grid.findall(qn("w:gridCol"))) if grid is not None else 0
56
+ ncols = max(ncols, 1)
57
+ cellmap: list[list[GridPos | None]] = []
58
+ for tr in trs:
59
+ row: list[GridPos | None] = [None] * ncols
60
+ col = 0
61
+ for tc in tr.findall(qn("w:tc")):
62
+ span, vmerge = parse_tc_props(tc)
63
+ while col < len(row) and row[col] is not None:
64
+ col += 1
65
+ if col + span > len(row):
66
+ row.extend([None] * (col + span - len(row)))
67
+ if vmerge == "continue":
68
+ for k in range(span):
69
+ row[col + k] = GridPos(None, False, "continue")
70
+ else:
71
+ for k in range(span):
72
+ row[col + k] = GridPos(tc, k == 0, vmerge, span)
73
+ col += span
74
+ cellmap.append(row)
75
+ ncols = max([len(row) for row in cellmap] + [ncols])
76
+ for row in cellmap:
77
+ row.extend([None] * (ncols - len(row)))
78
+ return trs, cellmap, ncols
79
+
80
+
81
+ def compute_merges(cellmap) -> list[tuple[int, int, int, int]]:
82
+ """返回 (起始行, 起始列, 行跨度, 列跨度)。"""
83
+ merges = []
84
+ for r, row in enumerate(cellmap):
85
+ for c, pos in enumerate(row):
86
+ if pos is None or not pos.owner:
87
+ continue
88
+ colspan = pos.span
89
+ rowspan = 1
90
+ if pos.vmerge == "restart":
91
+ rr = r + 1
92
+ while rr < len(cellmap):
93
+ nxt = cellmap[rr][c]
94
+ if nxt is None or nxt.vmerge != "continue":
95
+ break
96
+ rowspan += 1
97
+ rr += 1
98
+ merges.append((r, c, rowspan, colspan))
99
+ return merges
100
+
101
+
102
+ def cell_text(tc) -> str:
103
+ if tc is None:
104
+ return ""
105
+ parts = []
106
+ for p in tc.findall(qn("w:p")):
107
+ parts.append("".join(t.text or "" for t in p.iter(qn("w:t"))))
108
+ return "\n".join(parts)
109
+
110
+
111
+ def para_text(p) -> str:
112
+ return "".join(t.text or "" for t in p.iter(qn("w:t")))
113
+
114
+
115
+ def text_grid(tbl, cellmap) -> list[list[str]]:
116
+ grid = []
117
+ for row in cellmap:
118
+ grid.append([cell_text(pos.tc) if (pos is not None and pos.owner) else None for pos in row])
119
+ return grid
120
+
121
+
122
+ def header_rows(trs) -> set[int]:
123
+ result = set()
124
+ for idx, tr in enumerate(trs):
125
+ trPr = tr.find(qn("w:trPr"))
126
+ if trPr is not None and trPr.find(qn("w:tblHeader")) is not None:
127
+ result.add(idx)
128
+ return result
129
+
130
+
131
+ def cell_alignment(tc) -> tuple[str, str, bool]:
132
+ horizontal = "left"
133
+ for p in tc.findall(qn("w:p")):
134
+ pPr = p.find(qn("w:pPr"))
135
+ if pPr is None:
136
+ continue
137
+ jc = pPr.find(qn("w:jc"))
138
+ if jc is not None:
139
+ horizontal = JC_MAP.get(jc.get(qn("w:val")), "left")
140
+ break
141
+ vertical = "top"
142
+ tcPr = tc.find(qn("w:tcPr"))
143
+ if tcPr is not None:
144
+ va = tcPr.find(qn("w:vAlign"))
145
+ if va is not None:
146
+ vertical = VA_MAP.get(va.get(qn("w:val")), "top")
147
+ multiline = "\n" in cell_text(tc)
148
+ return horizontal, vertical, multiline
149
+
150
+
151
+ def table_borders(tbl) -> dict[str, str | None]:
152
+ """读取表级边框,作为 Excel 边框的默认值。"""
153
+ default = {"top": "thin", "bottom": "thin", "left": None, "right": None, "insideH": "dotted", "insideV": "dotted"}
154
+ tblPr = tbl.find(qn("w:tblPr"))
155
+ if tblPr is None:
156
+ return default
157
+ borders = tblPr.find(qn("w:tblBorders"))
158
+ if borders is None:
159
+ return default
160
+ result = dict(default)
161
+ for side in ("top", "left", "bottom", "right", "insideH", "insideV"):
162
+ el = borders.find(qn(f"w:{side}"))
163
+ if el is None:
164
+ continue
165
+ val = el.get(qn("w:val"))
166
+ if val in (None, "nil", "none"):
167
+ result[side] = None
168
+ else:
169
+ result[side] = BORDER_MAP.get(val, "thin")
170
+ return result
171
+
172
+
173
+ def explicit_borders(tc) -> dict[str, str | None]:
174
+ result: dict[str, str | None] = {}
175
+ tcPr = tc.find(qn("w:tcPr"))
176
+ if tcPr is None:
177
+ return result
178
+ borders = tcPr.find(qn("w:tcBorders"))
179
+ if borders is None:
180
+ return result
181
+ for side in ("top", "left", "bottom", "right"):
182
+ el = borders.find(qn(f"w:{side}"))
183
+ if el is None:
184
+ continue
185
+ val = el.get(qn("w:val"))
186
+ result[side] = None if val in (None, "nil", "none") else BORDER_MAP.get(val, "thin")
187
+ return result
188
+
189
+
190
+ def position_sides(borders: dict, r: int, c: int, nrows: int, ncols: int) -> dict[str, str | None]:
191
+ return {
192
+ "top": borders["top"] if r == 0 else borders["insideH"],
193
+ "bottom": borders["bottom"] if r == nrows - 1 else borders["insideH"],
194
+ "left": borders["left"] if c == 0 else borders["insideV"],
195
+ "right": borders["right"] if c == ncols - 1 else borders["insideV"],
196
+ }
197
+
198
+
199
+ def para_first_run_rpr(p_el):
200
+ """取段落第一个 run 的 rPr(没有 run 时退回段落标记的 rPr)。"""
201
+ if p_el is None:
202
+ return None
203
+ for run in p_el.findall(qn("w:r")):
204
+ rPr = run.find(qn("w:rPr"))
205
+ if rPr is not None:
206
+ return copy.deepcopy(rPr)
207
+ pPr = p_el.find(qn("w:pPr"))
208
+ if pPr is not None:
209
+ rPr = pPr.find(qn("w:rPr"))
210
+ if rPr is not None:
211
+ return copy.deepcopy(rPr)
212
+ return None