温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中利用pptx模块对ppt文件进行操作

发布时间:2020-12-28 14:29:49 来源:亿速云 阅读:243 作者:Leah 栏目:开发技术

本篇文章为大家展示了怎么在python中利用pptx模块对ppt文件进行操作,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

1. presentations

用于打开,创建,保存ppt文档,用法如下

>>> from pptx import Presentation
# 创建新的ppt文档
>>> prs = Presentation()
# 打开一个ppt文档
>>> prs = Presentation('input.pptx')
# 保存ppt文档
>>> prs.save('test.pptx')

2. slides

在创建一页ppt时,需要指定对应的布局,在该模块中, 内置了以下9种布局

1. Title

2. Title and Content

3. Section Header

4. Two Content

5. Comparison

6. Title Only

7. Blank

8. Content with Caption

9. Picture with Caption

通过数字下标0到9来访问,指定布局添加一页ppt的用法如下

>>> title_slide_layout = prs.slide_layouts[0]
>>> slide = prs.slides.add_slide(title_slide_layout)

3. shapes

shapes表示容器,在制作ppt时,各种基本元素,比如文本框,表格,图片等都占据了ppt的一个部分,或者矩形区域,或者其他各种自定义的形状。shapes表示所有基本元素的和, 通过如下方式来访问对应的shapes

shapes = slide.shapes

对于shapes而言,我们可以获取和设置其各种属性,比如最常用的text属性,用法如下

>>> shapes.text = 'hello world'

还可以通过add系列方法来添加各种元素,添加文本框的方法如下

>>> from pptx.util import Inches, Pt
>>> left = top = width = height = Inches(1)
>>> txBox = slide.shapes.add_textbox(left, top, width, height)
>>> tf = txBox.text_frame
>>> tf.text = "first paragraph"
>>> p = tf.add_paragraph()
>>> p.text = "second paragraph"

添加表格的方法如下

>>> rows = cols = 2
>>> left = top = Inches(2.0)
>>> width = Inches(6.0)
>>> height = Inches(0.8)
>>> table = shapes.add_table(rows, cols, left, top, width, height).table
>>> table.columns[0].width = Inches(2.0)
>>> table.columns[1].width = Inches(4.0)
>>> # write column headings
>>> table.cell(0, 0).text = 'Foo'
>>> table.cell(0, 1).text = 'Bar'

4. placeholders

shapes表示所有基本元素的总和,而placeholders则表示每一个具体的元素,所以placeholders是shapes的子集, 通过数字下标来访问对应的placeholder,用法如下

>>> slide.placeholders[1]
<pptx.shapes.placeholder.SlidePlaceholder object at 0x03F73A90>
>>> slide.placeholders[1].placeholder_format.idx
1
>>> slide.placeholders[1].name
'Subtitle 2'

placeholders是页面上已有的元素,获取对应的placeholders之后,可以通过insert系列方法来向其中新添元素。

了解上述层级结构,有助于我们对ppt的读写操作。除了写操作之外,也可以通过读操作来批量提取ppt中的特定元素,以文字为例,提取方式如下

from pptx import Presentation
 
prs = Presentation(path_to_presentation)
 
text_runs = []
 
for slide in prs.slides:
 for shape in slide.shapes:
  if not shape.has_text_frame:
   continue
  for paragraph in shape.text_frame.paragraphs:
   for run in paragraph.runs:
    text_runs.append(run.text)

通过该模块,可以快速搭建ppt的基本框架,也可以批量提取ppt中的特定元素,比如提取文字转换成word, 或者提取表格转换成excel文件。总而言之,该模块适合替代大量繁琐的人工复制粘贴操作。

上述内容就是怎么在python中利用pptx模块对ppt文件进行操作,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI