【Python】Excelに書き出す|pandas.ExcelWriter
作成日:2025-10-01
更新日:2025-10-01

pandasで書き込み
横・縦を選択して任意位置に書き込む
# Write a 1D array via pandas to an existing sheet at (row, col)
# pandasで任意位置に書き込む(横/縦を選択)
import pandas as pd
def pandas_write_1d(path, sheet_name, row, col, arr, horizontal=True, mode="a"):
"""
path: 既存/新規のExcelパス
row, col: 0-based offsets for pandas (startrow/startcol)
horizontal=True なら横1行、Falseなら縦1列
mode="a" で既存ブックに追記、"w" で新規作成
"""
if horizontal:
df = pd.DataFrame([list(arr)]) # 1行
else:
df = pd.DataFrame(list(arr)) # 1列
with pd.ExcelWriter(path, engine="openpyxl", mode=mode, if_sheet_exists="overlay") as xlw:
df.to_excel(xlw, sheet_name=sheet_name, index=False, header=False,
startrow=row, startcol=col)

pd.ExcelWriter, df.to_excel って?

窓口を開けて流し込むイメージ
pd.ExcelWriter|Excelファイルへの窓口(ドアノブ)
- 役割:Excelファイルを書き込み用に開く
- 引数:
path
|ファイルパスengine
|どのライブラリで書くか(openpyxl
,xlsxwriter
, etc.)mode
|"w"
=新規作成,"a"
=追記if_sheet_exists
|追記時の挙動(error
/new
/replace
/overlay
)
- 戻り値:ExcelWriterオブジェクト
with pd.ExcelWriter("report.xlsx", engine="openpyxl", mode="a", if_sheet_exists="overlay") as xlw:
...
ExcelWriterオブジェクト が「Excelファイルの窓口」になる
df.to_excel
|DataFrameの内容を、窓口に流し込む
- 役割:DataFrameの内容をExcelに書き込む = the data stream
- 主な引数:
excel_writer
|ExcelWriter
またはパス文字列sheet_name
|シート名index
|行番号を出力するか(True/False)header
|列名を出力するか(True/False)startrow
/startcol
|書き込み開始位置(0始まり)
df.to_excel(xlw, sheet_name="Summary", index=False, header=False, startrow=3, startcol=1)
ExcelWriter
は「窓口を開けるドアノブ」to_excel
は「そこへ水(DataFrameの内容)を流す」
※複数シートに書く/既存ブックに追記する/細かく制御するときは ExcelWriter
を with構文で使う
Referenced Insights & Citations
- pandas development team. (n.d.). pandas.DataFrame.to_excel. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html
- openpyxl. (n.d.). Worksheet objects. https://openpyxl.readthedocs.io/en/stable/worksheet.html
| ExcelWriter|エクセルライター |
| to_excel|to_excel |
| Workbook Handle|ブックハンドル |
| Data Stream|データストリーム |
| Context Manager|コンテキストマネージャ |
2025-10-01
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-
[Python]endswith+ lower 【Python】拡張子の存在確認|endswith + lower(Method Chaining) -
[Python]Stringsplit 【Python】文字列を抜き出す|split -
[Python]Search or Scanfor Excel book 【Python】ファイル名からExcelブックを取得する|openpyxl or win32com -
[Python]Excelto CSV 【Python】ExcelからCSVに書き出す|pandas,csv -
[Python]getdictionary 【Python】dictionaryから値を取得する2つの違い -
[Python]Excel datapandas.DataFrame 【Python】シートにあるデータを配列に格納する|pandas.DataFrame