LoginSignup
17
30

More than 5 years have passed since last update.

PythonでExcel書き込み

Posted at

背景

以前使用していたので備忘録用

使用ライブラリ

  • openpyxl

pip install openpyxl でインストールできます。
他のライブラリもありますがこちらを使用しました。

以下簡易的なコードを記載します。

ブック関連

import openpyxl

# 新規作成
book = openpyxl.Workbook()
# 既存ファイルオープン
book = openpyxl.load_workbook(filename='既にあるファイル.xlsx')
# 保存
book.save('ファイル.xlsx')
# 終了
book.close()

ワークシート関連

# シート設定
sheet = book.worksheets[0]
# シートのタイトル変更
sheet.title = 'サンプル'
# シート追加
new_sheet = book.create_sheet('追加シート')

セル書き込み

# 行と列を指定する、下記はセルA1を指します
sheet.cell(row=1, column=1).value = 123
# こちらの記法でも可能
sheet['A2'] = 456
# 参照も可能
sheet.cell(row=3, column=1).value = '=A1'
# セルの場所を特定したい場合はこちら
columns_str = openpyxl.utils.get_column_letter(1)
cell_str = columns_str + '2'
sheet.cell(row=4, column=1).value = '=' + cell_str
# Excelの関数も使用可能
sheet.cell(row=5, column=1).value = '=SUM(A1:A4)'

…結果は載せなくても分かりますよね?(笑)

総括

以上簡単なコードを記載しました。
openpyxl.styles.Fontなどを使用すれば文字を変更できますし、
openpyxl.chartを使用すればグラフ描画も可能です。

>>> dir(openpyxl)
['DEFUSEDXML', 'LXML', 'NUMPY', 'PANDAS', 'Workbook', '__author__', 
'__author_email__', '__builtins__', '__doc__', '__file__', '__license__',
 '__maintainer_email__', '__name__', '__package__', '__path__', '__url__',
 '__version__', '_constants', 'cell', 'chart', 'chartsheet', 'comments', 'compat',
 'constants', 'descriptors', 'drawing', 'formatting', 'formula', 'load_workbook',
 'packaging', 'pivot', 'reader', 'styles', 'utils', 'workbook', 'worksheet',
 'writer', 'xml']

色々用意されていますので、詳しくは公式ドキュメントを見るとよいでしょう。
https://openpyxl.readthedocs.io/en/stable/index.html

17
30
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
17
30