5
4

More than 1 year has passed since last update.

python-pptx 使い方

Last updated at Posted at 2022-03-07

Pythonを用いてPowerPointを操作したい

python-pptx というライブラリを用いて、
PowerPoint 操作を行ったので、その記録として残します。

公式ドキュメント

インストール

pip install python-pptx

必要な機能をインポート

import collections.abc # インポートしないとエラーが発生する
from pptx import Presentation # プレゼンテーションを作成
from pptx.util import Inches  # インチ
from pptx.enum.text import PP_ALIGN  # 中央揃えにする用
from pptx.util import Cm, Pt # センチ、ポイント
import collections.abc

上記のモジュールをインポートしないと
以下のエラーが発生します。

AttributeError: module 'collections' has no attribute 'Container'

pptxファイルの読み込み

新規でPowerPointファイルを作成

ppt = Presentation()

既存のファイルを読み込む

ppt = Presentation(filepath)

スライドレイアウトの読み込み

layout = ppt.slide_layouts[i]

インデックス番号によって、使用するスライドが異なります。

選択したスライドを追加

slide = ppt.slides.add_slide(layout)

テーブルの挿入

table = slide.shapes.add_table(row, col, x_pos, y_pos, width, height).table

表のスタイルを変更する

tbl = table._graphic_frame.element.graphic.graphicData.tbl
style_id = '{E8B1032C-EA38-4F05-BA0D-38AFFFC7BED3}'  # GUIDはgithub参照
tbl[0][-1].text = style_id

参照する GUID

表の幅を変更する。
例、columns[1] の幅を2インチに変更します。

table.columns[1].width = Inches(2)

フォント関連設定

table.cell(0, 0).text_frame.paragraphs[0].font.size = Pt(16)

# フォントの種類を指定する。

table.cell(0, 0).text_frame.paragraphs[0].font.name = 'メイリオ' # フォント名を指定
table.cell(0, 0).text_frame.paragraphs[0].font.italic = True # イタリック
table.cell(0, 0).text_frame.paragraphs[0].font.underline = True # アンダーラインを引く

# フォントを中央揃えにする。

table.cell(0, 0).text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER

作成したPowerPointを保存

ppt.save("./chart.pptx")

参考文献

やはり英語のドキュメントが読めると、
かなり作業効率が上がりますね。

積極的に読んで英語に慣れていこうと思います。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4