Python实现PPT表格的编写包含新建修改插图(收藏备用)

自动创建一个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")

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图灵学者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值