LoginSignup
10
14

More than 3 years have passed since last update.

いつも忘れる OpenPyXL

Last updated at Posted at 2020-05-13

インストール

pip install openpyxl

お約束

import openpyxl

基本

ワークブックの作成

wb = openpyxl.Workbook()
# 'Sheet'というワークブックが作成される

ワークブックの読込

wb = openpyxl.load_workbook('filename.xlsx')

ワークブックの保存

wb.save('output.xlsx')

ワークシートの作成

wb.create_sheet(title='title')
# titleを付与しない場合、 'Sheet'+番号(1~) で生成される

ワークシート名の変更

ws.title = 'new title'

ワークシート名の確認

wb.sheetnames

ワークシートの取得

ws = wb['title']

アクティブなワークシートの取得

ws = wb.active

セルの取得

cell = ws['A1']
cell = ws.cell(row=1, column=1)

セルに値を代入

cell.value = value

セルにハイパーリンクを付与

cell.hyperlink = 'url'

セルの幅を設定

ws.column_dimensions['A'].width = value

セルの座標を取得

cell.coordinate
# 文字列で取得される

セルの結合

ws.marge_cells('A1:A2')
ws.marge_cells(start_row=1, start_column=1, end_row=1, end_column=2)

スタイル

セルに色をつける

cell.fill = openpyxl.styles.PatternFill(fill_type='solid', fgColor='000000')

テキストの中央寄せ

cell.alignment = openpyxl.styles.Alignment(horizontal='center', vertical='center')

テキストの色を変える

cell.font = openpyxl.styles.Font(color='000000')

罫線

罫線を作成

side = openpyxl.styles.Side(style='thin')
border = openpyxl.styles.Border(left=side, right=side, top=side, bottom=side)

罫線を引く

cell.border = border

ユーティリティ

座標を分離(タプル化)

coordinate = openpyxl.utils.cell.coordinate_from_string('A1')
# coordinate -> ('A', 1)

列(アルファベット)を数字に変換

col = openpyxl.utils.cell.column_index_from_string('A')
col = openpyxl.utils.column_index_from_string('A')
# col -> 1

列(数値)をアルファベットに変換

col = openpyxl.utils.cell.get_column_letter(1)
col = openpyxl.utils.get_column_letter(1)
col -> 'A'

投稿者はチカラ尽きた。。。

そのうち増える

10
14
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
10
14