pptx在 PPT 里写入文字
要下载一个库
pptx
pip install python-pptx
与之前的类似
代码如下
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 13 11:12:40 2022
@author:Laney_Midory
csdn:Laney_Midory
"""
from curses.textpad import Textbox
from turtle import width
from pptx import Presentation
from pptx.util import Inches,Pt
ppt=Presentation()#初始化ppt
#插入幻灯片
slide=ppt.slides.add_slide(ppt.slide_layouts[1])
#方法一:获取ppt中的文本框
body_shape=slide.shapes.placeholders
#body_shape[0].text='这是占位符[0]'
#body_shape[1].text='这是占位符[1]'
#方法二:通过标题直接写入
title_shape=slide.shapes.title
title_shape.text='这是标题'
#除了标题之外下面的文本框只能用占位符获取
subtitle=slide.shapes.placeholders[1]
subtitle.text='这是文本框'
#在文本框中设置字体
new_paragraph=body_shape[1].text_frame.add_paragraph()#使用字体帧
new_paragraph.text='新段落'
new_paragraph.font.bold=True
new_paragraph.font.italic=True
new_paragraph.font.size=Pt(15)
new_paragraph.font.underline=True
#新加入一个文本框
left=Inches(2)
top=Inches(2)
width=Inches(3)
height=Inches(3)
textbox=slide.shapes.add_textbox(left,top,width,height)
textbox.text='这是新建的文本框'
new_para=textbox.text_frame.add_paragraph()
new_para.text='这是第二段'
ppt.save('C:/Users/Administrator/Desktop/excelcode/ppt/test.pptx')
套用 PPT 格式填入内容
这里主要是要定位文本框、段落、段落中每句话的位置
具体如下
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 13 11:12:40 2022
@author:Laney_Midory
csdn:Laney_Midory
"""
#改代码的难度主要在于如何定位要修改的部分的位置
from pptx import Presentation
ppt=Presentation('XXXX.pptx')#打开ppt
#打开第一个灯幻片
shape=ppt.slides[0].shapes
for i in shape:
print(i.text)
print('\n')
print(shape[1].text_frame.paragraphs[1].text)
print(shape[1].text_frame.paragraphs.runs[0].text)
#定位完成后 这里就是修改文字了
shape[1].text_frame.paragraphs.runs[0].text='更改后的文字'
ppt.save('C:/Users/Administrator/Desktop/excelcode/ppt/test3.pptx')