ppt母版
Placeholder占位符,类似于标题框
查看母版信息
from pptx import Presentation
prs=Presentation(‘XXX.pptx’)
slide=prs.slides.add_slide(prs.slide_layouts[0]) #prs.slide_layouts[0]获取第一个母版的第一个版式
for shape in slide.placeholders:
phf=shape.placeholder_format
print(’{}–{}–{}’.format(phf.idx,shape.name,phf.type))
shape.text=’{}–{}’.format(phf.idx,phf.type)
#shape.text=字符串
prs.save(‘XXX.pptx’)
根据占位符ID确定要填哪里
prs=Presentation(‘XXX.pptx’)
title_slide_layout=prs.slide_layouts[0]
slide=prs.slides.add_slide(title_slide_layout)
winner_name=slide.placeholders[0]
certificate_type=slide.placeholders[1]
this_is_to_certify_that=slide.placeholders[20]
winner_reason=slide.placeholders[19]
award_presenter=slide.placeholders[17]
award_date=slide.placeholders[21]
修改占位符的内容
winner_name.text=‘马冬梅’
certificate_type.text=‘学习奖’
this_is_to_certify_that.text=‘兹证明’
winner_reason.text=‘太难记了’
award_presenter.text=‘夏洛’
award_date.text=str(datetime.now().date())
添加段落paragraph
prs=Presentation(‘XXX.pptx’)
title_slide_layout=prs.slide_layouts[0]
slide=prs.slides.add_slide(title_slide_layout)
shapes=slides.shapes
title_shape=shapes.title
body_shape=shapes.placeholders[1]
title_shape.text=‘标题’
tf=body_shape.text_frame
tf.text=‘第一行’
p=tf.add.paragraph()
p.text=‘第二行’
prs.save(‘XXX.pptx’)
设定层级关系
p=tf.add.paragraph()
p.text=‘当前层’
p.lever=1
p=tf.add.paragraph()
p.text=‘当前层的下一层’
p.level=2
#0为最顶层
添加一个文本框
from pptx.util import Cm,Pt
prs=Presentation()
title_slide_layout=prs.slide_layouts[0]
slide=prs.slides.add_slide(title_slide_layout)
left=top=width=height=Cm(3)
text_box=slide.shapes.add_textbox(left,top,weight,height)
#slide.shapes.add_textbox(left,top,weight,height):添加一个文本框
tf=text_box.text_frame
tf.text=‘文本框的第一行文字’
p=tf.add.paragraph()
p.text=‘第二行文字,加粗,字号40’
p.font.bold=True
p.font.size=Pt(40)
prs.save(‘XXX.pptx’)
添加图片
from pptx.util import Cm
prs=Presentation()
title_slide_layout=prs.slide_layouts[0]
slide=prs.slides.add_slide(title_slide_layout)
left=top=Cm(3)
pic=slide.shapes.add_picture(‘XX.png’,left,top,height=None) #height可填可不填
添加表格
rows,cols=4,2
left=top=Cm(5)
width,height=Cm(18),Cm(3)
table=shapes.add_table(rows,cols,left,top,weight,height).table
table.columns[0].width=Cm(4)
table.rows[2].height=Cm[3]
data=[[2,3],[4,7]]
for row in range(rows):
for col in range(cols):
table.cell(row,col).text=str(data[row][col])
学习链接:https://www.bilibili.com/video/BV197411f7Rp