1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonで辞書を使ってエクセルに書き込む

Last updated at Posted at 2021-07-29

はじめに

openpyxlでエクセルにリスト(2次元配列)の書き込みを行う場合において,辞書で書き込みをするとオシャレになります.

excel.py
import openpyxl

wb = openpyxl.Workbook()
ws = wb.worksheets[0]

# ここに書き込んでいきます

wb.save('sample.xlsx')

リストでの書き込み

リストを使ってエクセルに書き込みます

list_excel.py
def write_list(ws, row, col, list_data):
    for y, list_value in enumerate(list_data):
        for x, value in enumerate(list_value):
            ws.cell(row=row+x, column=col+y, value=value)

list_data = [['nature', 1, 2, 3], ['prime', 2, 3, 5], ['Even', 2, 4, 6]]

write_list(ws, 1, 1, list_data)

#[('nature', 'prime', 'Even'),
# (1, 2, 2),
# (2, 3, 4),
# (3, 5, 6)]

辞書での書き込み

辞書を使ってエクセルに書き込みます

dict_excel.py
def write_dict(ws, row, col, dict_data):
    for y, (key, list_value) in enumerate(dict_data.items()):
        ws.cell(row=row, column=col+y, value=key)
        for x, value in enumerate(list_value):
            ws.cell(row=row+1+x, column=col+y, value=value)


dict_data = {'nature': [1, 2, 3], 'prime': [2, 3, 5], 'Even': [2, 4, 6]}

write_dict(ws, 1, 1, dict_data)

#[('nature', 'prime', 'Even'),
# (1, 2, 2),
# (2, 3, 4),
# (3, 5, 6)]

最後に

良きpythonライフを

参考

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?