python修改ppt中的文字部分及插入图片

批量修改ppt中的某个模块,或者批量制作奖状等场景会用到;

import os
import pandas as pd
from pptx import Presentation
from pptx.util import Inches

filepath='/Users/kangyongqing/Documents/kangyq/202303/分析模版/批量制作/'

file1='时段预警_副本.pptx'
file2='a.xlsx'
file3='001预警.png'

# PPT的基本结构介绍
#
# 在该模块中,将ppt拆分为了以下多个元素
#
# presentations, 表示整个ppt文档
# sliders. 表示ppt文档的每一页
# shapes 方框,在每页幻灯片内插入的方框,可以是形状,也可以是文本框
# Run 文字块 一般为较少字符
# Paragraph 段落,即Shape中的每一段内容,都称为一个段落


#读取excel
# df=pd.read_excel(filepath+file2)
#加载ppt模版
prs=Presentation(filepath+file1)
slide=prs.slides[0]
print(slide.shapes)

#替换所有文本集中的第一段文字
# for shape in slide.shapes:
#     print(shape)
#     if shape.has_text_frame:#判断是否存在文本
#         text_frame=shape.text_frame #获取shape中的文本
#         for paragraph in text_frame.paragraphs: #获取text_frame中的段落内容
#             print(paragraph.text) #打印段落内容
#         if text_frame.paragraphs:
#             text_frame.paragraphs[0].text='新的内容'



#替换指定文本集中的第二段文字
shape=slide.shapes[3]
if shape.has_text_frame:
    text_frame=shape.text_frame
    for paragraph in text_frame.paragraphs:
        print(paragraph)
    if text_frame.paragraphs:
        text_frame.paragraphs[2].text='单独修改'

image=filepath+file3
#计算图片在ppt中的位置
left,top,width,height=Inches(0.5),Inches(0.5),Inches(8),Inches(3)
#添加图片到ppt中
slide.shapes.add_picture(image,left,top,width=width,height=height)

# for i in slide.shapes.placeholders:
#     print(i.placeholder_format.idx)
# slide.placeholders[12].text='darin'




prs.save(filepath+'ceshi.pptx')




#替换占位符
#遍历DataFrame中的每一行记录,根据预设的位置替换幻灯片上的文本占位符。注意这里的占位符编号需要事先通过某种方式确定下来,比如查看模板文件或者运行一次脚本打印所有占位符索引。
# for i in range(df.shape[0]):
#     slide.placeholders[13].text=f'{df.loc[i,"姓名"]}同:'
#     #替换占位符的内容
#
#
#     prs.save(filepath+f'奖状-{df.loc[i,'姓名']}.pptx')
#
#     prs=Presentation(filepath+file1)
#     #每次循环后重置模板状态
#     slide=prs.slides[0]

修改后如下:

相关推荐
矛取矛求9 分钟前
C++ 模板初阶总结
开发语言·c++
杜子腾dd13 分钟前
13. Pandas :使用 to_excel 方法写入 Excel文件
大数据·python·数据挖掘·excel·numpy·pandas
Liuqz200925 分钟前
PPT 相关资料介绍
powerpoint
shix .1 小时前
爬虫一些基础知识的备忘录(需要自取)
c++·爬虫·python
19岁开始学习1 小时前
cgi,php-cgi,fastcgi,php-fpm,nginx 小记
开发语言·nginx·php
Vitalia1 小时前
⭐算法OJ⭐汉明距离【位操作】(C++ 实现)Hamming Distance
开发语言·c++·算法
小冯的编程学习之路1 小时前
【QT】:QT图形化界面相关准备工作
开发语言·c++·qt
龙雨LongYu122 小时前
Go执行当前package下的所有方法
开发语言·后端·golang
米饭好好吃.2 小时前
【Go】Go MongoDB 快速入门
开发语言·mongodb·golang
By北阳2 小时前
Go语言 vs Java语言:核心差异与适用场景解析
java·开发语言·golang