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ファイルに特定シートだけ書き換える方法

Posted at

【Python】複数シートのExcelファイルに特定シートだけ書き換える方法

こんにちは!今回は、Pythonで複数シートを持つExcelファイルを安全に更新する方法を紹介します。

例えば、

  • 「進捗管理」
  • 「案件管理」
  • 「履歴」
    みたいに複数シートがあるファイルで、特定のシートだけ上書きしたいケース、ありますよね。

📚 必要なライブラリ

まずは pandasopenpyxl を使います。

インストールしていない人は以下で入れておきましょう。

pip install pandas openpyxl

🐍 コード例

import pandas as pd

def update_excel_sheet(file_path, target_sheet, new_df):
    # ファイル内の全シートを読み込む
    sheets = pd.read_excel(file_path, sheet_name=None)

    # 更新したいシートだけ新しいデータフレームに置き換え
    sheets[target_sheet] = new_df

    # 全シートを書き戻す
    with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
        for sheet_name, df in sheets.items():
            df.to_excel(writer, sheet_name=sheet_name, index=False)

使用例

file_path = r'C:\共有フォルダ\管理表\業務管理.xlsx'
sheet_name = '進捗管理'

# 追加・更新したいデータ
push_df = pd.DataFrame({
    '案件名': ['案件A', '案件B'],
    'ステータス': ['完了', '進行中']
})

update_excel_sheet(file_path, sheet_name, push_df)

✨ この方法のメリット

  • 他のシートを壊さずに、特定のシートだけ更新できる!
  • openpyxl を使うので、.xlsxファイル対応もバッチリ
  • 新しくシートを追加したい場合も、この方法で簡単に対応できます。

✅ 注意点

  • ファイルパスは間違えないように注意。
  • 同時に別の人がファイルを開いているとエラーになる場合があります(共有フォルダ注意!)。

📌 まとめ

項目 内容
ライブラリ pandas / openpyxl
更新対象 指定した1シートのみ
特徴 複数シートがあっても安全に編集可能

💬 最後に

複数シートのExcel管理って地味に大変ですよね。
Pythonのちょっとしたテクニックで、毎日の更新作業を一気にラクにしましょう!

この記事が役に立ったら、ぜひ「いいね」やコメントお願いします!🙌


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?