PythonでPowerPointを結合する(asposeを使わずに)

ソフト

10個程度のパワーポイントを結合する必要があったので手作業で行うのはしんどいため、pythonを使って自動化した。asposeは優秀だが無料版では変な背景が消せないのでasposeを使わずにできる方法を紹介する。

準備

Powerpointがインストールされていることを確認したら、PythonからPowerPointの操作を行うためのライブラリをインストールする。また、新しいフォルダを作成しmergepptx.pyという名前のPythonファイルと大量のパワーポイントファイルを入れておく

python -m pip install --upgrade pywin32

以下のような内容のPythonファイルを作成する。Pythonファイル実行パスと同階層の01_…pptxから13.pptx までのファイルリストを順番に読み込み、merged2.pptxとして保存する。3行目のfilelist=の中にファイル名を結合したい順番で列挙していく。

import win32com.client
# your file list
filelist=["01_intro_2023.pptx","02_keitai_2023.pptx","04_privacy_2023.pptx","05-06_security_2023.pptx",
"07_culture_2023.pptx","08_bigdata_2023.pptx","09-10_tokkyo_2023.pptx","11-12_chosakuken_2023.pptx","13_ai1_2023.pptx",
"14_ai2_2023.pptx","15_media_2023.pptx"]
import os
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True
# open the rest PPTs
for i in range(0,len(filelist)):
    Application.Presentations.Open(os.getcwd()+"\\"+filelist[i])
# merge all PPTs
Application.Presentations[0].Slides.InsertFromFile(os.getcwd()+"\\"+filelist[0],0)
for i in range(1,len(filelist)):
    Application.Presentations[0].Slides.InsertFromFile(os.getcwd()+"\\"+filelist[i],Application.Presentations[0].Slides.Count)
# save the new PPT
Application.Presentations[0].SaveAs(os.getcwd()+"\\merged2.pptx")
# close the PPT
Application.Presentations[0].Close()
Application.Quit()

python3 mergepptx.py で実行すると大量にウィンドウが開かれ、すべてのウィンドウが閉じるとmerged2.pptxというファイルが出来上がっている。

おわりに

一気にすべてのファイルを開かずにできたと思う。あとファイルリストも手動でなく自動で取得することも可能だが、ファイル件数が少なかったので改良していない。もっと大量のファイルをマージするときはこのあたりを各自書き換えてほしい

コメント

タイトルとURLをコピーしました