简体   繁体   中英

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?

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)

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