Python-docx 复制表

问题描述 投票:0回答:2

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

这里
得到了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
时,它会复制带有新文本的表格。有没有办法“保存”表格,然后在对原始表格进行更改后复制原始表格?

python docx python-docx
2个回答
6
投票

是的,这应该是可能的:

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

0
投票

当我使用“copy_table_after(table, paragraph)”时,如果两个表彼此相邻,它们将合并。 我想复制一个表格并将其插入到原始表格之后,我尝试使用以下代码:

copied_table = deepcopy(table)
table._tbl.addnext(copied_table._tbl)

但是复制表和原始表合并了,我想得到两张表,我该怎么办?

© www.soinside.com 2019 - 2024. All rights reserved.