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]

修改后如下:

相关推荐
LCS-31216 分钟前
Python爬虫实战: 爬虫常用到的技术及方案详解
开发语言·爬虫·python
枫の准大一16 分钟前
【C++游记】List的使用和模拟实现
开发语言·c++·list
穷儒公羊17 分钟前
第二章 设计模式故事会之策略模式:魔王城里的勇者传说
python·程序人生·设计模式·面试·跳槽·策略模式·设计规范
qq_4335545424 分钟前
C++深度优先搜素
开发语言·c++·深度优先
心本无晴.29 分钟前
面向过程与面向对象
python
花妖大人30 分钟前
Python用法记录
python·sqlite
站大爷IP37 分钟前
用PyQt快速搭建桌面应用:从零到实战的实用指南
python
站大爷IP1 小时前
PyCharm:Python开发者的智慧工作台全解析
python
zhanghongyi_cpp1 小时前
linux的conda配置与应用阶段的简单指令备注
linux·python·conda
MThinker1 小时前
14.examples\01-Micropython-Basics\demo_yield.py 加强版
python·学习·智能硬件·micropython·canmv·k230