Python pptx 模块

1 投票
2 回答
3395 浏览
提问于 2025-04-18 01:42

我需要编辑一个pptx模板,这个模板里有像这样的表格:pptx table

我想把我在Python字典里存储的值填到这些空白的地方。现在我在用一个叫pptx的模块,但我找不到相关的例子来实现这个功能。

from pptx import Presentation


prs = Presentation('template.pptx')
slide = prs.slides[2] #<- This is the slide that contains the table
shape = slide.shapes #<- As I understood This gives access to the shapes
textframe=shape.textframe
textframe.clear()

prs.save('test.pptx') #<- Saves the new file

pptx模块链接

2 个回答

0


---in main----
table_data = [['ID', 'Name', 'Age', 'Second name'], ['1', 'Petro', 22, 'Petrovich'], ['2', 'Ivan', 32, 'Ivanovich'], ['3', 'Oles', 23, 'Marko']]

prs = Presentation(template_filepath)

slide_1 = slide_build(prs, 5)
table_draw(table_data, slide_1.shapes)
prs.save(result_filepath)


def slide_build(prs, layout):
    slide = prs.slides.add_slide(prs.slide_layouts[layout])
    return slide

def table_draw(table_data, shapes):
    rows_number = 0
    columns_number = 0

    # get table size
    rows_number = len(table_data)
    for i, item in enumerate(table_data):
        columns_number += 1

    table = table_build(rows_number, columns_number, shapes)

    column_coord = 0
    row_coord = 0

    for row_count, row in enumerate(table_data):
        for item_count, row_item in enumerate(row):
            table.cell(row_count + row_coord, item_count + column_coord).text = str(row_item)

def table_build(rows, cols, shapes):
    left = (0.1)
    top = Inches(0.7)
    width = Inches(6.0)
    height = Inches(0.8)
    table = shapes.add_table(rows, cols, left, top, width, height).table

    # set column widths
    i = 0
    while i 

像这样的一些东西

0

这是来自python-ppty开发者的开发小组的引用。

- 如果你知道它的索引,比如说 table = slide.shapes[2] 这样写就可以了。然后你需要先找到单元格,才能修改它们的内容:

for idx, row in enumerate(table.rows):
    if idx = 0:  # skip header row
        continue
    name_cell = row.cells[0]
    name_cell.text = 'foobar'
    corners_cell = row.cells[1]

撰写回答