Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tạo file PowerPoint với Python

Giới thiệu

Tạo PowerPoint bằng code Python thay vì dùng GUI. Thư viện python-pptx hỗ trợ Python 2.6–3.6.

Cài đặt

pip install python-pptx

Import

from pptx import Presentation

Tạo Presentation

X = Presentation()

9 layout (0-8): 0=Title Slide, 8=Picture with Caption.

Slide 1: Title Slide

Layout = X.slide_layouts[0]
first_slide = X.slides.add_slide(Layout)
first_slide.shapes.title.text = "Tạo PowerPoint bằng Python"
first_slide.placeholders[1].text = "Tạo bởi Tutorialspoint"
X.save("First_presentation.pptx")

Slide 2: Nội dung tùy chỉnh

from pptx.util import Inches
Second_Layout = X.slide_layouts[5]
second_slide = X.slides.add_slide(Second_Layout)
second_slide.shapes.title.text = "Slide thứ hai"

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 = "Đoạn văn trong slide thứ hai!"
X.save("First_presentation.pptx")

Ví dụ hoàn chỉnh

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 = "Tạo PowerPoint bằng Python"
first_slide.placeholders[1].text = "Tạo bởi Tutorialspoint"
X.save("First_presentation.pptx")
Second_Layout = X.slide_layouts[5]
second_slide = X.slides.add_slide(Second_Layout)
second_slide.shapes.title.text = "Slide thứ hai"
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 = "Đoạn văn trong slide thứ hai!"
X.save("First_presentation.pptx")

Kết luận

Đã tạo được PowerPoint bằng Python. Thư viện còn hỗ trợ: thêm ảnh, biểu đồ, thống kê... Xem tài liệu.