pythondocxpython-docx

Python-docx Copy Table


I have the following code which I am using to save a table, modify the table, and then make a copy of the table. I got copy_table_after() from Here.

def copy_table_after(table, paragraph):
    tbl, p = table._tbl, paragraph._p
    new_tbl = deepcopy(tbl)
    p.addnext(new_tbl)

def replaceText(document, search, replace):
    for table in document.tables:
        for row in table.rows:
            for paragraph in row.cells:
                if search in paragraph.text:
                    paragraph.text = replace

document = Document('Test.docx')
template = document.tables[0]
replaceText(document, '<<VALUE_TO_FIND>>', 'New value')
paragraph = document.add_paragraph()
copy_table_after(template, paragraph)

My problem is that when I run copy_table_after, it copies the table with the new text. Is there a way to 'save' the table and then make a copy of the original table after I have already made changes to it?


Solution

  • Yes, that should be possible like this :

    (Note that I have removed copy_table_after, because we just want to copy the table)

    def replaceText(document, search, replace):
        for table in document.tables:
            for row in table.rows:
                for paragraph in row.cells:
                    if search in paragraph.text:
                        paragraph.text = replace
    
    document = Document('Test.docx')
    template = document.tables[0]
    tbl = template._tbl
     # Here we do the copy of the table
    new_tbl = deepcopy(tbl)
    # Then we do the replacement
    replaceText(document, '<<VALUE_TO_FIND>>', 'New value')
    paragraph = document.add_paragraph()
    # After that, we add the previously copied table
    paragraph._p.addnext(new_tbl)