首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python-docx复制表

Python-docx复制表
EN

Stack Overflow用户
提问于 2018-02-10 04:16:04
回答 1查看 7.3K关注 0票数 1

我使用下面的代码来保存一个表,修改这个表,然后制作一个表的副本。我从Here那里得到了copy_table_after()

代码语言:javascript
复制
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时,它会用新文本复制表。有没有一种方法可以“保存”表,然后在我对其进行更改后复制原始表?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-10 06:26:58

是的,这应该是这样的:

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

代码语言:javascript
复制
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)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48713465

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档