我正在使用 python-docx 库来修改现有的 docx 文件。我想在文档的第五行添加一个表格。问题是,当我使用 document.add_table( ) 时,该表被添加到文档的末尾。我希望能够选择在文档中添加表格的位置。有什么办法可以做到这一点吗?我找不到任何在线可用的东西。
我试过这个:
from docx import Document
doc = Document('existing_document')
table_data = [
['Column 1', 'Column 2'],
['Data 1', 'Data 2'],
['Data 3', 'Data 4']
]
table = doc.add_table(rows=1,cols=2)
for i, row_data in enumerate(table_data):
row = table.rows[i]
for j, cell_data in enumerate(row_data):
row.cells[j].text = cell_data
doc.save('modified_document.docx')
当我执行此操作时,表格将添加到文档的末尾。
我尝试使用 insert_paragraph_before( ):
table = doc.add_table(rows=1,cols=2)
doc.paragraphs[5].insert_paragraph_before(table)
但是,这触发了一个错误,因为 insert_paragraph_before 似乎只适用于字符串。
是否必须使用python-docx?
通过分析您的代码,我意识到您正在使用模板'existing_document',因此,为了使用 docx 模板,我建议使用 docxtpl。
修改您的模板,并将一个或多个仅包含标题的空表格添加到文档中您喜欢的位置。
然后,您可以像这样简单地访问表:
from docxtpl import DocxTemplate
template = 'existing_document.docx'
output = 'output.docx'
doc = DocxTemplate(template)
# Reading tables
tables = doc.tables
first_table = tables[0]
# Supposing you added a table with 3 columns(Fruit, Color, price)
rows = [['apple','red','1.5'], ['banana', 'yellow', '0.75']]
# Adding rows
for row in rows:
table_row = first_table.add_row().cells
table_row[0].text = row[0]
table_row[1].text = row[1]
table_row[2].text = row[2]
doc.save(output)
使用 docxtpl 有很多方法可以实现相同的结果,所以请查看它的 文档