尝试将单元格与pythondocx合并

2024-06-20 15:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试合并docx文档的一组单元格,如下所示:

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)

table = document.add_table(rows=3, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

a = table.cell(0, 0)
b = table.cell(1, 1)
c = table.cell(2, 1)
d = table.cell(1, 2)

A = a.merge(b)
B = A.merge(c)
C = B.merge(d)

document.save('demo.docx')

但我得到:

Traceback (most recent call last):
  File "pdocx_error.py", line 32, in <module>
    C = B.merge(d)
  File "/home/martin/myvenv/lib/python3.8/site-packages/docx/table.py", line 232, in merge
    merged_tc = tc.merge(tc_2)
  File "/home/martin/myvenv/lib/python3.8/site-packages/docx/oxml/table.py", line 443, in merge
    top, left, height, width = self._span_dimensions(other_tc)
  File "/home/martin/myvenv/lib/python3.8/site-packages/docx/oxml/table.py", line 639, in _span_dimensions
    raise_on_tee_shaped(self, other_tc)
  File "/home/martin/myvenv/lib/python3.8/site-packages/docx/oxml/table.py", line 632, in raise_on_tee_shaped
    raise InvalidSpanError('requested span not rectangular')
docx.exceptions.InvalidSpanError: requested span not rectangular

这里怎么了


Tags: textinpyhomehdrlinetablecell
1条回答
网友
1楼 · 发布于 2024-06-20 15:20:18

让我们后退一点。以下是没有合并的表: no merges

这是必须合并的1,2单元: selected

然后执行前2次合并: merge 2

因此,我们可以清楚地看到,请求的合并将产生非矩形的内容。 但是,与下面的合并是可能的,因为它将生成一个rect,例如:

a = table.cell(0, 0)
b = table.cell(1, 1)
c = table.cell(2, 1)
d = table.cell(2, 2)

A = a.merge(b)
B = A.merge(c)
C = B.merge(d)

然后,前3行x 3列将合并为一行

相关问题 更多 >