Search code examples
pythonpython-docx

How to create table from function and add to docx document


I have working code that builds a document with several tables using a for-loop. To keep the code clean I would like to break out the table creation into its own function but cannot see how to do this from the API doc.

Essentially, I want to call a function to create & return a Table() object and then add it to the document.

Is this do-able?

# this works fine

from docx import Document, document, table

document = Document()

table1 = document.add_table(rows=1, cols=4)
     # more table1 building code here

table2 = document.add_table(rows=1, cols=4)
     # more table2 building code here 

document.save('foo.docx')

but refactoring like below will not build - I get TypeError: Table.init() got an unexpected keyword argument 'rows'

from docx import Document, document, table

document = Document()

document.add_table(build_mytable(somedata))
document.add_table(build_mytable(someotherdata))



def build_mytable(mydata):
    table = docx.table.Table(rows=1, cols=4)
    # more table building code here
    return table
    

Solution

  • maybe you try this;

    from docx import Document 
    
    
    def create_table(document):
        #this code creates a table with 2 rows and 2 columens 
        table = document.add_table(rows = 2 , cols = 2)
        #adding headers rows 
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = 'Item'     
        hdr_cells[1].text = 'quantity'
        
        #second riw 
        row_cells = table.add_row().cells 
        row_cells[0].text = 'Apple'
        row_cells[1].text = '10'
    
    
    document = Document()
    create_table(document)
    #save the file 
    document.save('tableName.docx')
    
    

    you can then use the add_paragraph method to add more text or other elements ; or the add_table method to add more tables

    for more info you can visit; Visit https://python-docx.readthedocs.io/en/latest/