搜索
您的当前位置:首页正文

python-pptx

来源:抵帆知识网
python-pptx

python-pptx的使⽤⾸先需要了解⼏个基本概念:1.引⼊python-pptx

frompptximportpresentation # 实例化Presentation prs= Presentation()2.ppt模板的选择a、使⽤ppt⾃带的模板 prs= Presentation()

prs.slide_layouts[index]

ppt⾃带了常⽤的1-48种模板通过index选择对应的模板b、使⽤⾃定义ppt模板

prs= Presentation('template.pptx')3.新建⼀页幻灯⽚

slide= prs.slides.add_slide(prs.slide_layouts[1]) # prs.slides.add_slide()增加⼀页幻灯⽚⽅法4.编辑幻灯中的元素

a、根据placeholdes索引获取⼀页幻灯⽚中的元素 body_shape= slide.shapes.placeholders # body_shape为本页ppt中所有shapes

body_shape[0].text= 'this is placeholders[0]' body_shape[1].text= 'this is placeholders[1]'

在ppt中所有的元素均被当成⼀个shape,slide.shapes表⽰幻灯⽚类中的模型类,placeholders中为每个模型,采⽤slide_layouts[1]中包含两个⽂本框,所以printlen(slide.shapes.placeholders) 话为2

b、获取幻灯⽚中的title元素(本页幻灯⽚必须含有标题元素才能通过此⽅法获取) title_shape= slide.shapes.title # 获取本页ppt的title元素

title_shape.text= 'this is a title'c、在本页幻灯⽚中新增元素

new_paragraph= body_shape[1].text_frame.add_paragraph() # 在第⼆个shape中的⽂本框中添加新段落

new_paragraph.text= 'add_paragraph'#新段落中的⽂字 ew_paragraph.font.bold= True # ⽂字加粗 new_paragraph.font.italic= True # ⽂字斜体

frompptx.utilimportPt#设置⽂字⼤⼩必须引⼊pptx.util中的Pt new_paragraph.font.size= Pt(15) # ⽂字⼤⼩

new_paragraph.font.underline= True # ⽂字下划线new_paragraph.level = 1 # 新段落的级别5.新增幻灯中的元素a、添加新⽂本框

frompptx.utilimportInches

left= top= width= height= Inches(5) # 预设位置及⼤⼩

textbox= slide.shapes.add_textbox(left, top, width, height) # left,top为相对位置,width,height为⽂本框⼤⼩ textbox.text= 'this is a new textbox'

# ⽂本框中⽂字

new_para= textbox.text_frame.add_paragraph() # 在新⽂本框中添加段落

new_para.text= 'this is second para in textbox' # 段落⽂字b、添加图⽚

img_path= 'img_path.jpg' # ⽂件路径

left, top, width, height= Inches(1), Inches(4.5), Inches(2), Inches(2) # 预设位置及⼤⼩

pic= slide.shapes.add_picture(img_path, left, top, width, height) # 在指定位置按预设值添加图⽚c、添加形状

frompptx.enum.shapesimportMSO_SHAPE

left, top, width, height= Inches(1), Inches(3), Inches(1.8), Inches(1) # 预设位置及⼤⼩

shape= slide.shapes.add_shape(MSO_SHAPE.PENTAGON, left, top, width, height) # 在指定位置按预设值添加类型为PENTAGON的形状 shape.text= 'Step 1' forninrange(2, 6):

left= left+width-Inches(0.3)

shape= slide.shapes.add_shape(MSO_SHAPE.CHEVRON, left, top, width, height) shape.text= 'Step{}'.format(n)d、添加表格

rows, cols, left, top, width, height= 2, 2, Inches(3.5), Inches(4.5), Inches(6), Inches(0.8) table= slide.shapes.add_table(rows, cols, left, top, width, height).table # 添加表格,并取表格类

table.columns[0].width= Inches(2.0) # 第⼀纵列宽度

table.columns[1].width= Inches(4.0) # 第⼆纵列宽度

table.cell(0, 0).text= 'text00' # 指定位置写⼊⽂本

table.cell(0, 1).text= 'text01' table.cell(1, 0).text= 'text10' table.cell(1, 1).text= 'text11'

因篇幅问题不能全部显示,请点此查看更多更全内容

Top