Search code examples
pythonpython-3.xpython-docx

Replace text in docx tables in Python 3


I'm using python-docx and trying to replace text in table saving styles. that's how my table looks

I've managed with replacing paragraph using this:

from docx import Document
def replace_string(doc, to_replace, replacement):
    for p in doc.paragraphs:
        if to_replace in p.text:
            inline = p.runs
            for i in range(len(inline)):
                if to_replace in inline[i].text:
                    text = inline[i].text.replace(to_replace, replacement)
                    inline[i].text = text
    return 1

But it doesn't work with tables and cells. I also tried this:

def replace_in_table(doc, to_replace, replacement):
for table in doc.tables:
    for cell in table.cells:
        for p in cell.paragaphs:
            if to_replace in p.text:
                inline = p.runs
                for i in range(len(inline)):
                    if to_replace in inline[i].text:
                        text = inline[i].text.replace(to_replace, replacement)
                        inline[i].text = text
return 1

But I have an AttributeError: 'Table' object has no attribute 'cells'. Please, help me to solve this problem


Solution

  • Looking at their docs you probably need to do something like this:

    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
               ...