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')

效果图如下
python办公自动化-----pptx_第1张图片
4. 定位:定位某列里面的某个文本框里面的具体run
定位如下图的段落
python办公自动化-----pptx_第2张图片

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')

你可能感兴趣的:(pptx)