Search Posts

Visits: 4

1. pptxインストール

python-pptxは、PyPIから公開されているので、pipでインストールする。

pip install python-pptx

2. 原稿ファイル(CSV)からパワーポイントを作成

CSVファイル

Table 1. input.csv

page

level

text

1

最初のページのタイトル.

1

1

先頭ページの1行目

1

2

先頭ページの2行目

2

第2ページのタイトル

2

1

第2ページの1行目

最初のページ

Table 2. 最初のページのタイトル.

Level

Text

1

先頭ページの1行目

2

先頭ページの2行目

2ページ

Table 3. 第2ページのタイトル

Level

Text

1

第2ページの1行目

3. PythonプログラムpptxSlide.py

pptxSlide.py
import argparse
import csv
from pptx import Presentation
from pptx.util import Inches

def read_csv(input_csv):
    """
    CSVファイルを読み込み、行の辞書のリストを返します。
    """
    sections = []  # 各セクションを格納するためのリスト
    current_section_title = None  # 現在のセクションのタイトル
    current_section_content = []  # 現在のセクションのコンテンツ
    with open(input_csv, mode='r', encoding='utf-8-sig') as file:
        reader = csv.DictReader(file)
        for row in reader:
            # キーと値の前後の空白を削除
            row = {k.strip(): v.strip() for k, v in row.items()}
            page, level, text = row['page'], row['level'], row['text']

            if not level:  # 新しいセクションの開始
                if current_section_title is not None:
                    # 前のセクションを保存
                    sections.append({"title": current_section_title, "content": current_section_content})
                    current_section_content = []  # 次のセクションの準備
                current_section_title = text  # 新しいタイトルの設定
            else:
                # 現在のセクションにコンテンツを追加
                level = int(level) - 1  # レベルを0から開始するように調整
                current_section_content.append({"text": text, "level": level})
        # 最後のセクションを追加するのを忘れない
        if current_section_title is not None:
            sections.append({"title": current_section_title, "content": current_section_content})
    return sections


def add_slide_with_textboxes_and_paragraphs(presentation, title_text, content_list):
    slide_layout = presentation.slide_layouts[1]  # 空白のレイアウトを使用
    slide = presentation.slides.add_slide(slide_layout)  # PPTファイルにスライドオブジェクトを追加
    myShapes = slide.shapes  # shapesの属性にアクセス
    titleShape = myShapes.title  # タイトルにテキストを追加
    titleShape.text = title_text
    bodyShape = myShapes.placeholders[1]  # 本文テキストフレームを追加
    textFrame = bodyShape.text_frame
    first_paragraph = True  # 最初の段落が重複しないようにする
    for paragraph in content_list:
        if first_paragraph:
            p = textFrame
            first_paragraph = False
        else:
            p = textFrame.add_paragraph()
        p.text = paragraph["text"]
        p.level = paragraph["level"]


def create_presentation(sections, output_pptx, presentation):
    """
    提供されたデータからPowerPointプレゼンテーションを作成し、保存します。
    """
    for section in sections:
        title_text = section['title']
        content_list = section['content']
        add_slide_with_textboxes_and_paragraphs(presentation, title_text, content_list)
    presentation.save(output_pptx)
    print(f"プレゼンテーション {output_pptx} が正常に作成されました。")


def main():
    # 引数パーサーの設定
    parser = argparse.ArgumentParser(description='CSVファイルからPPTXプレゼンテーションを作成します。')
    parser.add_argument('input_csv', type=str, help='入力CSVファイルのパス')
    parser.add_argument('output_pptx', type=str, help='出力PPTXファイルのパス')
    # 引数を解析
    args = parser.parse_args()
    # CSVからデータを読み込む
    sections = read_csv(args.input_csv)
    # PowerPointプレゼンテーションを初期化
    presentation = Presentation()
    # プレゼンテーションを作成して保存
    create_presentation(sections, args.output_pptx, presentation)

if __name__ == "__main__":
    main()
sections
[
    {'title': '最初のページのタイトル.', 'content': [
        {'text': '先頭ページの1行目', 'level': 0},
        {'text': '先頭ページの2行目', 'level': 1}
    ]},
    {'title': '第2ページのタイトル', 'content': [
        {'text': '第2ページの1行目', 'level': 0}
    ]}]

Page1

Page2

4. 実行方法

python pptxSlide.py input.csv output.pptx

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です