Search code examples
pythonpython-3.xpython-docx

How to write multiple tables in docx file using python-docx?


I want to write/include more than two tables in a docx file using python. How can I write this structure as a table in a docx file using python?

I tried the following code for a single table. Now I would like to create 2 tables in a single docx.

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()

Solution

  • You just need a loop to create your tables. Let's say you need 5 tables:

    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')