如何在 MS Word 文档中指定要添加表格的位置

问题描述 投票:0回答:1

我正在使用 python doc.add_table 方法生成一个 word 文档。 word文档末尾自动生成表格。如何指定应在文档中添加此表格的位置?

我尝试过使用各种对齐方法,但到目前为止都没有奏效

python python-docx
1个回答
0
投票

假设你有一个文件

t1.docx
像:

并且您想在第 2 段和第 3 段之间插入表格。您可以通过以下方式实现:

from docx import Document

doc = Document('t1.docx')

# the table you want to insert at position
tbl = doc.add_table(rows=1, cols=2) # actually inserts table at the bottom of the document, but we'll move it to the target location
tbl.style = 'Table Grid'
row = tbl.rows[0]
row.cells[0].text = 'hey'
row.cells[1].text = 'hoo'
tbl_el = tbl._element

# find target place to move table to
target_el = None
for p in doc.paragraphs:
    if p.text == 'Paragraph 2':
        target_el = p._element


# insert after the target element (actually moves existing element to that location)
parent_el = target_el.getparent()
parent_el.insert(parent_el.index(target_el)+1, tbl_el)

doc.save('t2.docx')

就这样结束了

t2.docx

© www.soinside.com 2019 - 2024. All rights reserved.