Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 812
tee Avatar asked Mar 19 '26 19:03

tee


1 Answers

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

like image 183
Neil Avatar answered Mar 22 '26 08:03

Neil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!