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