1.创建ppt
首先下载pip3 install python-potx库
import pptx
# 生成ppt对象
p = pptx.Presentation()# 选中布局
layout = p.slide_layout[1]# 把布局加入到生成的ppt中
slide = p.slides.add_slide(layout)# 保存ppt
p.save('test.pptx')
2.ppt段落的使用
import pptx# 生成ppt对象
p = pptx.Presentation()# 选布局
layout = p.slide_layouts[1]slide = p.slides.add_slide(layout)# 段落的使用
# 0表示标题 1表示文本内容title = slide.placeholders[0]
# 设置标题
title.text= "test标题"# 设置内容
placeholder = slide.palceholders[1]placeholder.text = "111\n222"# 保存
p.save('test2.pptx')
3.创建多个段落
import pptx
from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT
from pptx.util import Ptp = pptx.Presemtation()layout = p.slide_layouts[1]slide = p.slides.add_layouts(layout)title = slide.placeholders[0]# 设置标题
title.text = "titletest"placeholder = slide.placeholder[1]
paragraph1 = placeholder.text_frame.add_paragraph()paragraph.text = '这是一个段落'# 设置段落格式
paragraph.bold = True
paragraph.font.italic = True
paragraph.font.size = Pt(16)
parahraph.alignment = PP_PARAGRAPH_ALIGNMENT.CENTER# ... 可以继续使用 placeholder.text_frame.add_paragraph() 继续添加段落# 保存文件
p.save('test3.pptx')
4.自定义段落
import pptx
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT
from pptx.util import Inches, Ptp = pptx.Presentation()layout = p.slide_layouts[1]slide = p.slides.add_slide(layout)# left和top 是文本框距离 左侧和顶部的距离 width和height 是宽高
left = top = width = height =Inches(5)# 定义文本框
box = slide.shapes.add_textbox(left,top,width,height)
# 给文本框添加段落
para_box = box.text_frame.add_paragraph()
para_box.text = '这是一个自定义的段落'# 设置格式
para_box.alignment = PP_PARAGRAPH_ALIGNMENT.CENTER
para_box.font.size = Pt(30)
para_box.font.color.rgb = RGBColor(255,0,0)
para_box.font.name = '微软雅黑'# 保存
p.save('test4.pptx')
5.添加表格
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT
from pptx.util import Inches, Ptp = pptx.Presentation()# 选中布局
layout = p.slide_layouts[1] # 选中第一种布局slide = p.slides.add_slide(layout)# 定义几行几列
rows = 10
cols = 2# 定义位置
left = top = Inches(2)
# 定义宽高
width = Inches(6)
height = Inches(1)# 生成表格
table = slide.shapes.add_table(rows,col,left,top,width,height).table# 遍历给单元格添加数据
for index,_ in enumerate(range(rows)):for sub_index in range(cols):table.cell(index,sub_index).text = "%s:%s" % (index,sub_index)# 保存ppt
p.save('test5.pptx')
6.添加图片
import pptx
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT
from pptx.util import Inches, Ptp = pptx.Presentation()layout = p.slide_layouts[1]slide = p.slides.add_slide(layout)slide.shapes.add_picture(images_file='1.jpg',width=Inches(6),height=Inches(4))# 保存
p.save('test6.pptx')
7.读取ppt
import pptx p = pptx.Presentation('test5.pptxt')for slide in p.slides:for shape in slide.shapes:# 判断是否是文本框if shape.has_text_frame:print(shape.text_frame.text)# 判断是否是表格if shape.has_table:# 遍历表格for row in shape.table.rows:for cell in row.cells:print(cell.text)