gpt4 book ai didi

Python-docx 复制表

转载 作者:行者123 更新时间:2023-11-30 22:21:07 25 4
gpt4 key购买 nike

我有以下代码,用于保存表、修改表,然后复制表。我从 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 复制表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48713465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com