Python-docx 复制 Table

Python-docx Copy Table

我有以下代码,用于保存 table、修改 table,然后复制 table。我从 Here.

得到了 copy_table_after()
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)

我的问题是,当我 运行 copy_table_after 时,它会用新文本复制 table。有没有办法 'save' table 然后在我已经对它进行更改后制作原始 table 的副本?

是的,应该可以这样:

(注意我已经删除了copy_table_after,因为我们只想复制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)