How to keep the table cell text format while updating the table in docx python

https://stackoverflow.com/questions/73487377/how-to-keep-the-table-cell-text-format-while-updating-the-table-in-docx-python

@regularshy There are more elegant ways to fill a template with data using Aspose.Words than simply setting table cells text. For example you can consider using Mail Merge. In this case you put mergefields where data must be inserted and them execute mail merge in the code. Currently, Python version supports only simple mail merge. Another more powerful option is using LINQ Reporting Engine.

But if you need simple put new text into the table cell preserving its formatting, you should first understand the table cell content representation. It looks like this:


So to preserve original formatting it is required to put new text into the appropriate Run node. The problem is that cell can contain more then one paragraph and each paragraph can contain zero or more Run nodes with different font formatting. See Aspose.Words Document Object Model for more information.
If your table is simple (one paragraph with one run per cell) then you can use code like this to update cell content:

doc = aw.Document("C:\\Temp\\in.docx")

# Get table
table = doc.first_section.body.tables[0]

# update text in cells
for r in table.rows :
    row = r.as_row()
    for c in row.cells :
        cell = c.as_cell()
        cell.first_paragraph.runs[0].text = "this is new text"

doc.save("C:\\Temp\\out.docx")

in.docx (12.5 KB)
out.docx (9.9 KB)