使用 win32com.client 透過 COM 介面操作 PowerPoint,可實現開啟現有簡報、在指定位置插入新投影片、並向投影片中加入圖片等自動化操作。這對於批量生成標準化簡報極為實用。
# -*- coding: UTF-8 -*-
import win32com.client
import os
def insert_slide_with_image():
ppt_path = os.path.join(os.getcwd(), "BugCurve.pptx")
img_path = os.path.join(os.getcwd(), "This_is_Picture.png")
app = win32com.client.Dispatch("PowerPoint.Application")
app.Visible = True
presentation = app.Presentations.Open(ppt_path)
# 在第 2 頁(封面之後)插入空白投影片,版面配置代碼 12 代表空白版面
new_slide = presentation.Slides.Add(2, 12)
# 在新投影片中插入圖片,設定位置與大小
shape = new_slide.Shapes.AddPicture(
img_path,
LinkToFile=False,
SaveWithDocument=True,
Left=40, Top=100, Width=650, Height=400
)
presentation.Save()
presentation.Close()
app.Quit()
if __name__ == "__main__":
insert_slide_with_image()
Slides.Add(Index, Layout):Index 為插入位置(1-based),Layout 為版面配置常數(12 = ppLayoutBlank 空白版面)。Shapes.AddPicture:LinkToFile=False 表示將圖片嵌入文件而非連結;SaveWithDocument=True 確保儲存時包含圖片資料。Left、Top 為左上角位置,Width、Height 為尺寸。可進一步封裝為函式,支援批量插入、替換佔位符圖片、根據資料動態生成圖表等。結合 python-pptx 純 Python 庫(無需安裝 Office)可實現跨平台操作,但 win32com 方案能完整利用 PowerPoint 原生渲染與動畫效果。