python办公自动化-----pptx

安装第三方库:pip install python-pptx
注意:python文件命名不要跟模块名一样,否则会报错,如 pptx.py这样的文件名

  1. 以下是对文本框添加文字的部分
from pptx import Presentation
from pptx.util import Inches,Pt

ppt = Presentation()
slide = ppt.slides.add_slide(ppt.slide_layouts[1]) #在ppt中插入一个幻灯片

body_shape = slide.shapes.placeholders
# body_shape[0].text = '这是占位符0'
# body_shape[1].text = '这是占位符1'

title_shape = slide.shapes.title
title_shape.text = '这是标题123'
# subtitle = slide.shapes.placeholders[1] #取出本页第二个文本框
# subtitle.text = '这里是文本框'

#在第二个框框假如一段文字
# new_paragraph = body_shape[1].text_frame.add_paragraph()
# new_paragraph.text = '新段落'
# new_paragraph.font.bold = True #字体加粗
# new_paragraph.font.italic = True  #字体斜体
# new_paragraph.font.size = Pt(20)  # 字体大小
# new_paragraph.font.underline = True  #加文字下划线

#在第二个文本框里面自定义一个新文本框并写入文字
left = Inches(2)
top = Inches(2)
width = Inches(3)
height = Inches(3)

textbox = slide.shapes.add_textbox(left, top, width, height)
textbox.text = '这是新文本框'
new_para = textbox.text_frame.add_paragraph()
new_para.text = '这是新文本框里面的第二段'

ppt.save('test.pptx')

2 . 以下是往ppt里面添加一张图片

from pptx import Presentation
from pptx.util import Inches,Pt

# 注意:python文件命名不要跟模块名一样,否则会报错,如 pptx.py的文件名

ppt = Presentation()
slide = ppt.slides.add_slide(ppt.slide_layouts[1]) #在ppt中插入一个幻灯片

left = Inches(2)
top = Inches(2)
width = Inches(3)
height = Inches(3)

pic = slide.shapes.add_picture('pic.jpg', left, top, width, height)

ppt.save('test.pptx')
  1. 往ppt里面加入表格
from pptx import Presentation
from pptx.util import Inches,Pt

# 注意:python文件命名不要跟模块名一样,否则会报错,如 pptx.py的文件名

ppt = Presentation()
slide = ppt.slides.add_slide(ppt.slide_layouts[1]) #在ppt中插入一个幻灯片

left = Inches(2)
top = Inches(2)
width = Inches(3)
height = Inches(3)


rows = 2
cols =2
left = Inches(1)
top = Inches(1)
width = Inches(4)
height = Inches(4)
table = slide.shapes.add_table(rows, cols, left, top, width, height).table
table.columns[0].width = Inches(1)
table.columns[1].width = Inches(3)

table.cell(0, 0).text = '1'
table.cell(0, 1).text = '1'
table.cell(1, 0).text = '1'
table.cell(1, 1).text = '1'

ppt.save('test.pptx')

效果图如下
在这里插入图片描述
4. 定位:定位某列里面的某个文本框里面的具体run
定位如下图的段落
在这里插入图片描述

from pptx import Presentation
from pptx.util import Inches,Pt

# 注意:python文件命名不要跟模块名一样,否则会报错,如 pptx.py的文件名

ppt = Presentation('mode.pptx')

shape = ppt.slides[0].shapes

for i in shape:  #打印出来每个shape
	print(i.text)
	print('\n') 

print(shape[1].text_frame.paragraphs[1].text)
print(shape[1].text_frame.paragraphs[1].run[0].text)
shape[1].text_frame.paragraphs[1].runs[0].text = '更改后的新段落'


ppt.save('test.pptx')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值