自动创建一个ppt文件并创建好表格
代码要用到pptx库
pip install python-pptx
创建含有表格的ppt文件代码:
from pptx import Presentation
from pptx.util import Inches
# 创建一个PPT对象
ppt = Presentation()
# 添加一个幻灯片
slide = ppt.slides.add_slide(ppt.slide_layouts[5])
# 设置幻灯片大小
slide_width = ppt.slide_width
slide_height = ppt.slide_height
# 添加表格
rows, cols = 5, 6
table = slide.shapes.add_table(rows, cols, left=Inches(0), top=Inches(0), width=slide_width, height=slide_height).table
# 填充表格内容
for i in range(rows):
for j in range(cols):
table.cell(i, j).text = f"单元格({i+1}, {j+1})"
# 保存PPT文件
ppt.save('new-example.pptx')
结果如下:
新建一个ppt文件
from pptx import Presentation
# 创建一个新的PPT文档
prs = Presentation()
# 创建第一页
slide_1 = prs.slides.add_slide(prs.slide_layouts[0])
title_1 = slide_1.shapes.title
title_1.text = "First Slide"
content_1 = slide_1.placeholders[1]
content_1.text = "This is the content on the first slide"
# 创建第二页
slide_2 = prs.slides.add_slide(prs.slide_layouts[1])
title_2 = slide_2.shapes.title
title_2.text = "Second Slide"
content_2 = slide_2.placeholders[1]
content_2.text = "This is the content on the second slide"
# 保存PPT文档
prs.save("sample.pptx")
在PPT中插入图片
from pptx import Presentation
from pptx.util import Inches
# 创建一个新的PPT文档
prs = Presentation()
# 创建页面
slide = prs.slides.add_slide(prs.slide_layouts[5])
# 插入图片
img_path = "image.png"
left_inch = Inches(1)
top_inch = Inches(2)
width_inch = Inches(5)
height_inch = Inches(4)
slide.shapes.add_picture(img_path, left_inch, top_inch, width_inch, height_inch)
# 保存PPT文档
prs.save("sample_with_image.pptx")
修改ppt内容
from pptx import Presentation
# 打开一个已有的PPT文档
prs = Presentation("sample.pptx")
# 遍历每一页,并修改标题
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
if shape.text_frame.text == "First Slide":
shape.text_frame.text = "Modified First Slide"
elif shape.text_frame.text == "Second Slide":
shape.text_frame.text = "Modified Second Slide"
# 保存修改后的PPT文档
prs.save("sample_modified.pptx")