在自動化辦公流程中,將 PowerPoint 簡報轉換為圖片檔是常見需求。本文詳細介紹如何使用 Python 透過 COM 元件操作 Microsoft PowerPoint,實現簡報頁面的批量截圖與匯出,支援指定頁碼、自訂解析度等進階功能。
執行此程式碼前,請確認本機已安裝 Microsoft PowerPoint,並安裝 comtypes 套件:
pip install comtypes
此方法透過 Windows COM 介面直接呼叫 PowerPoint 應用程式,因此僅支援 Windows 作業系統。
以下函式可將指定的 .ppt/.pptx 檔案匯出為 JPG 圖片序列:
import os
import comtypes.client
def export_presentation(ppt_path, output_folder):
"""
將 PowerPoint 簡報匯出為圖片
參數:
ppt_path: 簡報檔案完整路徑
output_folder: 輸出資料夾路徑
"""
# 路徑驗證
if not (os.path.isfile(ppt_path) and os.path.isdir(output_folder)):
raise ValueError("請提供有效的檔案與資料夾路徑!")
# 建立 PowerPoint 應用程式物件
powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
powerpoint.Visible = True # 設為 False 可在背景執行
try:
# 開啟簡報檔
presentation = powerpoint.Presentations.Open(ppt_path)
# 匯出所有頁面為 JPG(預設 96 DPI)
presentation.Export(output_folder, "JPG")
# 進階用法:指定頁面與解析度
# presentation.Slides[1].Export("C:/output/slide1.jpg", "JPG", 1920, 1080)
finally:
# 確保資源釋放
presentation.Close()
powerpoint.Quit()
# 使用範例
if __name__ == "__main__":
export_presentation(r"C:\briefing\report.pptx", r"C:\output\images")
False 可隱藏 PowerPoint 視窗,提升批次處理效能Q: 執行時出現 "Access Denied" 錯誤?
A: 請確認 PowerPoint 未被其他程序佔用,且輸出資料夾具備寫入權限。
Q: 如何匯出特定頁面而非全部?
A: 使用 presentation.Slides[index].Export(...),索引從 1 開始。
此技術廣泛應用於:自動化報表生成、簡報內容預覽縮圖、線上教學教材轉檔、文件管理系統的縮圖生成等場景。搭配排程器可實現定時批次轉檔,大幅減少人工操作成本。