Search code examples
pythonpython-2.7ms-worddocxpython-docx

Edit table in word docx using Python


How can I edit an already existing table in a word document using Python. Let's say inside my word document i have a table with only 2 rows and I want to add more rows in Python, how can i do this? I've tried with docx library but the best I can do with this is creating a table and saving it to a word document.

I want to edit an already existing table. Thanks!


Solution

  • Code

    You can do this in the docx library, by accessing .tables from a Document.

    from docx import Document
    
    doc = Document('grid.docx')
    doc.tables #a list of all tables in document
    print("Retrieved value: " + doc.tables[0].cell(0, 0).text)
    doc.tables[0].cell(0, 0).text = "new value"
    doc.tables[0].add_row() #ADD ROW HERE
    doc.save("grid2.docx")
    

    From

    enter image description here

    To

    enter image description here