inset batch picture into ppt

本文介绍了一种使用Python批量将图表图片插入到PowerPoint演示文稿的方法。通过定义每页的布局,自动计算图片的位置,并批量处理图片路径,实现了自动化生成包含多个图表的PPT。此方法适用于数据可视化报告的快速制作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from pptx import Presentation
from pptx.util import Inches
from pptx.util import Length

def insert_chart_ppt(test_items):
    prs = Presentation()

    # left = 0  # this is x axis
    # top = 0  # this is y axis
    row_count = 3
    column_count = 4
    width = prs.slide_width / getattr(Length, "_EMUS_PER_INCH")
    height = prs.slide_height / getattr(Length, "_EMUS_PER_INCH")
    row_height = (height - 0.5) / row_count
    column_width = (width - 0.5) / column_count

    # () means generator, if generator is used out, you can't use it again
    rows = list(x * row_height for x in range(row_count))
    columns = list(y * column_width for y in range(column_count))

    img_paths = []
    for item in test_items:
        img_paths.append("analog_" + item.desc + ".png")
        if len(img_paths) == row_count * column_count:
            batch_insert(img_paths, prs, rows, columns)
            img_paths.clear()

    if len(img_paths) > 0:
        batch_insert(img_paths, prs, rows, columns)

    prs.save('chart_insert.pptx')
 
 def batch_insert(img_paths, prs, rows, columns):
    blank_slide_layout = prs.slide_layouts[6]
    slide = prs.slides.add_slide(blank_slide_layout)

    pic_width = Inches(3)
    pic_height = Inches(2.27)

    for row_index, row in enumerate(rows):
        for columns_index, column in enumerate(columns):
            index = row_index*len(columns) + columns_index
            if index < len(img_paths):
                img_path = img_paths[index]
                print("Insert {} into ppt".format(img_path))
                slide.shapes.add_picture(img_path, Inches(column), Inches(row), height=pic_height, width=pic_width)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值