python-pptxとは
python-pptxは、PythonでPowerPointのファイルやスライドを作成・編集することができるライブラリです。
python-pptxのインストール
python-pptxはAnacondaには同梱されていないので、pipやsetup.pyなどを使ってインストールする必要があります。
pip install python-pptx
python-pptxの基本的な使い方
プレゼンテーションの作成と保存
from pptx import Presentation
prs = Presentation()
スライドの追加
layout = prs.slide_layouts[i]
slide = prs.slides.add_slide(layout)
テキストボックスの挿入
textbox = slide.shapes.add_textbox(Inches(1), Inches(1), Inches(2), Inches(1))
frame = textbox.text_frame
p = frame.add_paragraph()
p.text = "Hello, World!"
表の作成
table = slide.shapes.add_table(row, col, x_pos, y_pos, width, height).table
グラフの作成
グラフの作成は少し複雑ですが、以下のようなコードで可能です。
chart_data = CategoryChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Series 1', (19.2, 21.4, 16.7))
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
chart = slide.shapes.add_chart(
XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data
).chart
画像の挿入
left = top = Inches(1)
pic = slide.shapes.add_picture(img_path, left, top)
文字のスタイルを変更
run = p.add_run()
run.text = "bold"
font = run.font
font.bold = True
まとめ
以上がpython-pptxの基本的な使い方です。これらの基本操作を組み合わせることで、PythonからPowerPointを自由自在に操作することが可能になります。