0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python × Excel】複数の.xlsxファイルを結合してCSV出力するツールを作ってみた

Posted at
1 / 2

はじめに

複数のExcelファイルから、特定の列だけを抽出して1つのCSVにまとめるPythonスクリプトを作成しました。
日付順に並べたり、金額に桁区切りを入れたりする工夫もしています。

使用技術

  • Python 3.x
  • pandas
  • openpyxl

やりたかったこと

  • 毎月届くExcelファイル(同じ形式)を自動でまとめたい
  • 特定の列(例:日付・名前・金額)だけ取り出したい
  • 最後にCSV形式で出力したい

実装したコード

import pandas as pd
import os

# 入力フォルダと出力ファイルの指定
INPUT_FOLDER = "input_excel"
OUTPUT_FILE = "output.csv"

# 抽出したい列のインデックス(0から始まる)
# 例:A列 = 0, C列 = 2, F列 = 5
COLUMNS_TO_EXTRACT = [0, 2, 5]
COLUMN_NAMES = ["日付", "名前", "金額"]

# 結果を入れるリスト
all_data = []

# フォルダ内のExcelファイルをすべて処理
for filename in os.listdir(INPUT_FOLDER):
    if filename.endswith(".xlsx"):
        file_path = os.path.join(INPUT_FOLDER, filename)

        try:
            # Excelファイルを読み込む(最初のシート)
            df = pd.read_excel(file_path, sheet_name=0, engine="openpyxl")

            # 指定列だけ取り出し
            extracted = df.iloc[:, COLUMNS_TO_EXTRACT]
            extracted.columns = COLUMN_NAMES

            # 元ファイル名を列に追加
            extracted["元ファイル"] = filename

            all_data.append(extracted)
        except Exception as e:
            print(f"[エラー] {filename} の読み込み中に問題が発生しました: {e}")

# 全部まとめて1つのDataFrameに
if all_data:
    combined_df = pd.concat(all_data, ignore_index=True)

    # "日付"列のフォーマットを変更する
    combined_df["日付"] = pd.to_datetime(combined_df["日付"], errors="coerce").dt.strftime("%Y/%m/%d")

    # "日付"順に並べ替える
    combined_df = combined_df.sort_values(by="日付", ascending=True)

    # "金額"列に桁区切りを追加
    combined_df["金額"] = combined_df["金額"].apply(lambda x: "{:,.0f}".format(x))

    # 出力CSVとして保存
    combined_df.to_csv(OUTPUT_FILE, index=False, encoding="utf-8-sig")
    print(f"[成功] {OUTPUT_FILE} を出力しました。")
else:
    print("[注意] 対象となるファイルがありませんでした。")

工夫した点

  • 日付を「2024/02/01」のように見やすく整形
  • 金額に桁区切り(カンマ)を入れて視認性アップ
  • エラーハンドリングも最低限追加

まとめ

pandasはデータの整形にとても便利です。
日々の作業効率化にこうした小さなツールを作っていきたいと思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?