Python-docx复制表 [英] Python-docx Copy Table

查看:35
本文介绍了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时,它会用新文本复制表。有没有一种方法可以‘保存’该表,然后在我对其进行更改后复制原始表?

推荐答案

是的,应该是这样的:

(请注意,我删除了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)

这篇关于Python-docx复制表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆