Python-docx复制表

时间:2018-02-09 20:16:04

标签: python docx python-docx

我有以下代码用于保存表,修改表,然后复制表。我从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时,它会使用新文本复制表格。有没有办法拯救&#39;在我已经对其进行更改后,该表然后制作原始表的副本?

1 个答案:

答案 0 :(得分:1)

是的,应该可以这样:

(请注意,我已删除了copy_table_after,因为我们只想复制表格)

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)