[Python] How to create table from function and add to docx document

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página