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'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM