LoginSignup
19
16

More than 5 years have passed since last update.

[python]DataFrameを利用して既存Excelファイルのシートを編集・追加する方法

Last updated at Posted at 2018-02-20

単一シートのexcelファイルの書き出し・読み込み・編集はよく行いますが、単純にsheet_nameだけを指定するのではそのシート以外が削除されてしまいます。これを知らずに既存のファイルにシートを追加して保存しようとしたとき、少々手間取ったのでメモとして残します。

既存excelファイルに新しいシートを追加する方法

edit_sheet.py

import pandas as pd
import openpyxl as opx

# 対象ファイルのExcelWriterの呼び出し
EXL=pd.ExcelWriter('file_path', engine='openpyxl')

# ExcelWriterに既存の対象ファイルを読み込ませる
EXL.book=opx.load_workbook('file_path')
# 既存のsheet情報を読み込ませる
EXL.sheets=dict((ws.title, ws) for ws inEXL.book.worksheets)

# ExcelWriterを用いて新規シートにDataFrameを保存
df.to_excel(EXL, sheet_name='sheet_name', index=False)

# ExcelWriterの処理を保存
EXL.save()

indexの指定はお好みで

19
16
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
19
16