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]

修改后如下:

相关推荐
酒尘&10 小时前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
冬夜戏雪10 小时前
【java学习日记】【2025.12.7】【7/60】
java·开发语言·学习
xwill*10 小时前
分词器(Tokenizer)-sentencepiece(把训练语料中的字符自动组合成一个最优的子词(subword)集合。)
开发语言·pytorch·python
咖啡の猫11 小时前
Python列表的查询操作
开发语言·python
Chiandra_Leong11 小时前
Python-Pandas、Numpy
python·pandas
BoBoZz1911 小时前
ParametricObjectsDemo多种参数曲面展示及面上部分点法线展示
python·vtk·图形渲染·图形处理
quikai198111 小时前
python练习第三组
开发语言·python
JIngJaneIL11 小时前
基于Java非遗传承文化管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
吃西瓜的年年12 小时前
1. 初识C语言
c语言·开发语言
ULTRA??12 小时前
初学protobuf,C++应用例子(AI辅助)
c++·python