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]

修改后如下:

相关推荐
励志成为糕手12 分钟前
编程语言Java——核心技术篇(六)解剖反射:性能的代价还是灵活性的福音?
java·开发语言·intellij-idea
yourkin66613 分钟前
Bean Post-Processor
java·开发语言·前端
晨非辰17 分钟前
#C语言——学习攻略:深挖指针路线(五)--回调函数,qsort函数,qsort函数的模拟实现
c语言·开发语言·经验分享·学习·visual studio
大飞pkz26 分钟前
【Lua】题目小练3
开发语言·lua·题目小练
这里有鱼汤26 分钟前
全网最通俗易懂的趋势判断神器:卡尔曼滤波原来这么实用!
后端·python·程序员
天天开心(∩_∩)31 分钟前
代码随想录算法训练营第三十七天
java·开发语言·算法
这里有鱼汤37 分钟前
年化96%的小市值策略的选股逻辑源码来了
后端·python
都叫我大帅哥1 小时前
当知识图谱遇上RAG:GraphRAG全解指南
python·ai编程
FF-Studio1 小时前
25年电赛C题 发挥部分 YOLOv8方案&数据集
python·深度学习·yolo
mortimer1 小时前
Tenacity:一行代码实现简洁优雅的遇错自动重试逻辑
人工智能·python·网络协议