首页 > 解决方案 > 如何使用 python-docx 在 docx 文件中编写多个表?

问题描述

我想使用 python 在 docx 文件中写入/包含两个以上的表。如何使用 python 将此结构写为 docx 文件中的表?

我为单个表尝试了以下代码。现在我想在一个 docx 中创建 2 个表。

table = document.add_table(rows=rows_no,cols=1)

Timeline = row[5]
print (row[0],row[3],"Timing:",row[5])
cells = table.add_row().cells
cells[0].paragraphs[0].add_run( Compliance_requirements).bold = True
cells[0].paragraphs[1].add_run( "Obs: "+Finding_Description).text = True
cells[0].paragraphs[2].add_run( "requitements: "+requirements).text = True
cells[0].paragraphs[3].add_run( "Timeline: Need"+Timeline+" days of notice period .").text = True

document.add_paragraph()

标签: pythonpython-3.xpython-docx

解决方案


你只需要一个循环来创建你的表。假设您需要 5 张桌子:

number_of_tables = [1, 2, 3, 4, 5]
document = Document()

for k in number_of_tables:
    table = document.add_table(rows=2, cols=3, style='Light Grid')
    # Here add your content

    document.add_paragraph('Adding space between tables')

document.save('my_test.docx')

推荐阅读