简体   繁体   中英

Replace existing table in Word doc using python docx

I have a Word document with the following tables:

doc = Document('doc_generator.docx')
print(doc.tables)

[docx.table.Table object at 0x0000017E8B2A0D68, docx.table.Table object at 0x0000017E8B2A0198]

and I am trying to replace one of the existing tables with a new one. What I have done is:

doc.tables[0] = new_table

with new_table being an actual Word docx table, ie running:

type(new_table)

returns:

docx.table.Table

If I then try to save the updated document via:

doc.save('Updated.docx')

The table is still not updated. If instead I run a command as eg :

doc.tables[0].add_row()

The table is actually updated in the Word doc. It seems the problem is my assignment statement. Any idea how to solve this? I do want to replace , not edit or update, an existing table with a new one via python-docx. Thanks in advance.

You could use the .replace method for the parent xml object:

doc.element.body.replace(old_table._element, new_table._element)

Where both 'old_table' and 'new_table' are docx.table.Table objects. The ._element attribute accesses the table object within the doc's xml structure.

If doc.element.body is not the parent element of the table, you can find the parent using:

old_table._element.getparent()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM