Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้างไฟล์ PowerPoint ด้วย Python (python-pptx)

บทนำ

python-pptx สร้าง/แก้ไข PowerPoint (.pptx) ด้วยโค้ด Python รองรับ Python 2.6–3.6+

การติดตั้ง

pip install python-pptx

สร้าง Presentation พื้นฐาน

from pptx import Presentation
X = Presentation()

# Layout 0 = Title Slide
Layout = X.slide_layouts[0]
first_slide = X.slides.add_slide(Layout)
first_slide.shapes.title.text = "Creating a powerpoint using Python"
first_slide.placeholders[1].text = "Created by Tutorialpoints"

X.save("First_presentation.pptx")

เพิ่ม Slide ที่ 2 พร้อม Textbox

from pptx.util import Inches
Second_Layout = X.slide_layouts[5]  # Blank layout
second_slide = X.slides.add_slide(Second_Layout)
second_slide.shapes.title.text = "Second slide"

textbox = second_slide.shapes.add_textbox(Inches(3), Inches(1.5), Inches(3), Inches(1))
textframe = textbox.text_frame
paragraph = textframe.add_paragraph()
paragraph.text = "This is a paragraph in the second slide!"

X.save("First_presentation.pptx")

คำอธิบาย

  • 9 layouts (0-8): 0=Title, 1=Title+Content, 2=Section Header, 3=Two Content, 4=Comparison, 5=Title Only, 6=Blank, 7=Content with Caption, 8=Picture with Caption
  • placeholders[1] = subtitle placeholder ใน Title slide
  • Inches จาก pptx.util ใช้ระบุตำแหน่ง/ขนาดในนิ้ว
  • add_textbox(left, top, width, height) → text_frame → add_paragraph()

โค้ดตัวอย่างครบถ้วน

from pptx import Presentation
from pptx.util import Inches

X = Presentation()
Layout = X.slide_layouts[0]
first_slide = X.slides.add_slide(Layout)
first_slide.shapes.title.text = "Creating a powerpoint using Python"
first_slide.placeholders[1].text = "Created by Tutorialpoints"
X.save("First_presentation.pptx")

Second_Layout = X.slide_layouts[5]
second_slide = X.slides.add_slide(Second_Layout)
second_slide.shapes.title.text = "Second slide"
textbox = second_slide.shapes.add_textbox(Inches(3), Inches(1.5), Inches(3), Inches(1))
textframe = textbox.text_frame
paragraph = textframe.add_paragraph()
paragraph.text = "This is a paragraph in the second slide!"
X.save("First_presentation.pptx")

คุณสมบัติเพิ่มเติม

เพิ่มรูปภาพ, ตาราง, ชาร์ท, SmartArt, animation, slide transitions, master slides, ฯลฯ

เอกสาร: https://python-pptx.readthedocs.io/