Python pptx模块

2024-04-25 17:26:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须编辑包含如下表的pptx模板:pptx table

如何将python dict中存储的值附加到空字段中? 我使用的是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 module link


Tags: 模块the模板编辑thispresentationdict例子
2条回答

引自python ppty developer的dev组

-如果你知道它的索引,类似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]


 -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 

像这样的东西

相关问题 更多 >