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]

修改后如下:

相关推荐
virtual_k1smet22 分钟前
#rsa.md
笔记·python
一个天蝎座 白勺 程序猿23 分钟前
Python驱动Ksycopg2连接和使用Kingbase:国产数据库实战指南
数据库·python·kingbase·金仓数据库
兰亭妙微34 分钟前
兰亭妙微QT软件开发与UI设计协同:如何避免设计与实现脱节?
开发语言·qt·ui
1710orange1 小时前
java设计模式:动态代理
java·开发语言·设计模式
开心-开心急了2 小时前
PySide6 文本编辑器(QPlainTextEdit)实现查找功能——重构版本
开发语言·python·ui·重构·pyqt
郝学胜-神的一滴2 小时前
Effective Python 第39条:通过@classmethod多态来构造同一体系中的各类对象
开发语言·python·程序人生·软件工程
IT森林里的程序猿3 小时前
基于Python的招聘信息可视化分析系统
开发语言·python
卷Java3 小时前
用户权限控制功能实现说明
java·服务器·开发语言·数据库·servlet·微信小程序·uni-app
Derrick__13 小时前
Python常用三方模块——psutil
开发语言·python
winrisef3 小时前
删除无限递归文件夹
java·ide·python·pycharm·系统安全