使用 python-pptx 包附加表格行将添加一行,在 PowerPoint 中编辑时会更改另一行的内容

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

我正在使用 python-pptx 包将 PowerPoint 演示文稿读入 Python。没有本机支持将行(或列)插入表对象。尽管许多人根据下面的 GitHub 线程提出了与此类似的解决方法:

from pptx import Presentation
from pptx.table import _Cell

prs = Presentation('test.pptx')
TAB = prs.slides[1].shapes[1].table
copy_idx=0
insert_idx=1
new_row = copy.deepcopy(TAB._tbl.tr_lst[copy_idx])
for tc in new_row.tc_lst:
    cell = _Cell(tc, new_row.tc_lst)
    cell.text = 'foobar'
TAB._tbl.append(new_row)
prs.save('test.pptx')

https://github.com/scanny/python-pptx/pull/399

当您打开 PowerPoint 演示文稿时,如果您单击添加的行并开始键入,它将修改第一行中的文本,而不是新添加的行中的文本。保存并重新启动应用程序可以使问题消失。然而,当我需要继续处理 python 中的演示对象而不必停下来手动重新启动 PowerPoint 时,这还不够好。

python-3.x powerpoint python-pptx
1个回答
0
投票

问题确实是deepcopy结果。您绝对正确地将罪魁祸首识别为 a16:rowId 属性值。一个快速但肮脏的解决方案:

        new_row = copy.deepcopy(TAB._tbl.tr_lst[copy_idx])  # copies row element with styleIndex
    id_attrib = new_row.getchildren()[-1].getchildren()[0].getchildren()[0] # get the id attribute from newly copied row
    row_id = insertIndex if insertIndex != -1 else len(self)+1 # increase row id by row number
    id_attrib.set("val", str(int(id_attrib.get("val")) + row_id)) # set the value
© www.soinside.com 2019 - 2024. All rights reserved.