史上最全的Python操作 PPT 文档大全,以后写数据分析报告靠它了( 三 )

效果如下:
史上最全的Python操作 PPT 文档大全,以后写数据分析报告靠它了文章插图
③ 给段落设定层级关系import pptxfrom pptx import Presentationprs = Presentation("finall.pptx")slide = prs.slides.add_slide(prs.slide_layouts[0])name = slide.placeholders[14]why = slide.placeholders[15]name.text = "黄同学"why.text = "学习太积极"# --------------------------------------------------- #prs1 = Presentation("finall.pptx")slide1 = prs.slides.add_slide(prs.slide_layouts[1])shapes = slide1.shapestitle_shape = shapes.title # 这句代码可以改为title_shape = shapes.placeholders[0]body_shape = shapes.placeholders[1]title_shape.text = "这是一个标题"tf = body_shape.text_frametf.text = "带圆点的符号1"p = tf.add_paragraphp.text = "带圆点的符号2"# 原始内容的层级相当于是0 , 因此这个段落我设置为层级1 , 下面的段落设置为层级2p.level = 1p = tf.add_paragraphp.text = "带圆点的符号3"p.level = 2prs.save("嘻嘻.pptx")效果如下:
史上最全的Python操作 PPT 文档大全,以后写数据分析报告靠它了文章插图
④ 添加一个文本框

  • slide.shapes.add_textbox(left, top, width, height)
from pptx import Presentationfrom pptx.util import Cm, Ptprs = Presentation# 使用第一个版式black_slide_layout = prs.slide_layouts[0]slide = prs.slides.add_slide(black_slide_layout)left = top = width = height = Cm(3)text_box = slide.shapes.add_textbox(left, top, width, height)tf = text_box.text_frametf.text = "这是一段文本框里面的文字"p = tf.add_paragraphp.text = "这是第二段文字 , 加粗 , 字号40"p.font.bold = Truep.font.size = Pt(40)prs.save("添加一个文本框0.pptx")效果如下:
史上最全的Python操作 PPT 文档大全,以后写数据分析报告靠它了文章插图
⑤ 添加一个图片
  • slide.shapes.add_picture(图片路径, 距离左边, 距离顶端, 宽度, 高度)
第一种展示:
from pptx import Presentationfrom pptx.util import Cmprs = Presentation# 使用第七个版式black_slide_layout = prs.slide_layouts[6]slide = prs.slides.add_slide(black_slide_layout)left = top = Cm(3)pic = slide.shapes.add_picture("孙悟空.png", left, top)prs.save("添加图片1.pptx")效果如下:
史上最全的Python操作 PPT 文档大全,以后写数据分析报告靠它了文章插图
第二种展示:
from pptx import Presentationfrom pptx.util import Cmprs = Presentation# 使用第七个版式black_slide_layout = prs.slide_layouts[6]slide = prs.slides.add_slide(black_slide_layout)left = top = Cm(3)height = Cm(5.5)pic = slide.shapes.add_picture("孙悟空.png", left, top, height=height)prs.save("添加图片2.pptx")效果如下:
史上最全的Python操作 PPT 文档大全,以后写数据分析报告靠它了文章插图
⑥ 添加表格
  • shapes.add_table(rows, cols, left, top, width, height)
from pptx import Presentationfrom pptx.util import Cm, Ptprs = Presentation# 使用第七个版式black_slide_layout = prs.slide_layouts[6]slide = prs.slides.add_slide(black_slide_layout)shapes = slide.shapesrows, cols = 5, 3left = top = Cm(5)width = Cm(18)height = Cm(3)table = shapes.add_table(rows, cols, left, top, width, height).tabletable.columns[0].width = Cm(6)table.columns[1].width = Cm(2)table.columns[2].width = Cm(2)table.rows[0].height = Cm(2)data = http://kandian.youth.cn/index/[["姓名","性别","成绩"],["张三","男",96],["李四","女",87],["王五","女",90],["赵六","男",78]]for row in range(rows):for col in range(cols):table.cell(row,col).text = str(data[row][col])prs.save("插入表格.pptx")