有没有办法在 PowerPoint 幻灯片 Python 中向 table 添加一列?

Is there a way to add a column to a table in PowerPoint slide through Python?

我有一个 powerpoint 模板,我想用它来创建月度报告。幻灯片中 table 之一的列数可能会根据某些逻辑发生变化,我想在运行时添加新列。

我一直在寻找一种添加列的方法,但找不到。 python-pptx 文档在 _ColumnCollection class 下列出了一个 add(before) 方法,但我认为还没有可用。

有谁知道有什么方法可以做到这一点吗?

创建一个新的 table 所需形状。

>>> shape = table_placeholder.insert_table(rows=..., cols=...)
>>> table = shape.table

将上一个 table 中的内容复制到新的 table。 此外,请在此处添加新值。示例代码:

>>> cell_old = table_old.cell(0, 0)
>>> cell_new = table_new.cell(0, 0)
>>> cell_new.text = cell_old.text

删除旧的table。

我编写了一个函数,将旧的 table 更改为新的 table

使用此函数,您可以扩展新 table 并填充旧 table

中的相同值

假设我们有一个 table 有 2 行和 4 列

[1,2,3,4]
[1,2,3,4]

并且您想将它扩展 4 行和 6 列并填充与旧 table

相同的值
[1,2,3,4,5,6]
[1,2,3,4,5,6]
[1,2,3,4,5,6]
[1,2,3,4,5,6]

我的代码

def changeTable(new_table,old_table):
        rowIndex = 0
        cellIndex = 0
        for row in old_table.rows:
            for cell in row.cells:
                new_table.cell(rowIndex,cellIndex).text = cell.text
                cellIndex = cellIndex + 1
            cellIndex = 0    
            rowIndex = rowIndex + 1

old_table = shp.table
new_table = slide.shapes.add_table(4,6,shp.left,shp.top,shp.width,shp.height).table
changedTable = changeTable(new_table,old_table)