Python

Excelデータを集計して
グラフ付きレポートを自動生成

売上データのExcelファイルを読み込み、月別・商品別に集計してグラフ付きのレポートExcelを自動生成するPythonスクリプトです。

Python 3 pandas openpyxl matplotlib Excel出力
処理の流れ
📊
Excel読み込み
pandas で取得
🔢
集計処理
月別・商品別
📈
グラフ生成
matplotlib
💾
Excel出力
openpyxl で保存
スクリプト(Python)
Python 3excel_report.py
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
from datetime import datetime
import io

matplotlib.use('Agg')  # 画面表示なしで描画

def generate_report(input_file: str, output_file: str):
    # --- データ読み込み ---
    df = pd.read_excel(input_file)
    df['日付'] = pd.to_datetime(df['日付'])
    df['月']   = df['日付'].dt.strftime('%Y-%m')

    # --- 月別売上集計 ---
    monthly = df.groupby('月')['売上金額'].sum().reset_index()
    monthly.columns = ['月', '合計売上']

    # --- 商品別売上集計 ---
    by_product = df.groupby('商品名')['売上金額'].sum()\
                   .sort_values(ascending=False).reset_index()

    # --- グラフ生成(月別棒グラフ)---
    fig, ax = plt.subplots(figsize=(10, 4))
    ax.bar(monthly['月'], monthly['合計売上'], color='#2d7a4f')
    ax.set_title('月別売上推移', fontsize=14)
    ax.set_ylabel('売上金額(円)')
    ax.tick_params(axis='x', rotation=45)
    plt.tight_layout()

    img_buf = io.BytesIO()
    fig.savefig(img_buf, format='png', dpi=150)
    img_buf.seek(0)
    plt.close()

    # --- Excelに集計表+グラフを書き込み ---
    with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
        monthly.to_excel(writer, sheet_name='月別集計', index=False)
        by_product.to_excel(writer, sheet_name='商品別集計', index=False)

    # グラフ画像をシートに貼り付け
    wb   = load_workbook(output_file)
    ws   = wb['月別集計']
    img  = Image(img_buf)
    img.anchor = 'D2'
    ws.add_image(img)
    wb.save(output_file)

    print(f"✅ レポートを {output_file} に出力しました")

if __name__ == '__main__':
    today = datetime.now().strftime('%Y%m%d')
    generate_report('sales_data.xlsx', f'report_{today}.xlsx')
ポイント解説
📊
pandas で高速集計 groupby を使うことで、数千行のデータも一瞬で月別・商品別に集計できます。
📈
グラフをExcelに直接埋め込み matplotlib で生成した棒グラフを BytesIO 経由でExcelシートに貼り付け。ファイル一つで完結するレポートを生成します。
📅
日付付き出力ファイル名 毎月実行しても上書きされず、report_20250601.xlsx のように月次レポートを蓄積できます。