Last active
January 30, 2021 15:15
-
-
Save kotoripiyopiyo/333b580048dc46608d33e65f7b693738 to your computer and use it in GitHub Desktop.
openpyxlの機能チートシートスクリプト(初級)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# まとめ | |
import openpyxl | |
from openpyxl.utils import get_column_letter, column_index_from_string | |
# Workbookオブジェクトを取得して情報を表示 | |
print('● 開始') | |
wb = openpyxl.load_workbook('example.xlsx') # ワークブック読み込むんでWorkbookオブジェクトを取得 | |
print(f'typeは{type(wb)}、シート一覧は{wb.sheetnames}、アクティブなシートは{wb.active}') | |
print('終了\n') | |
# Worksheetオブジェクトを取得して情報を表示 | |
print('● 開始') | |
sheet = wb['Sheet1'] | |
print(f'最大行数は{sheet.max_row}、最大列数は{sheet.max_column}') | |
print('終了\n') | |
# セルの値を取得して情報を表示 | |
print('● 開始') | |
onecell = sheet['B1'] | |
print(f'行:{onecell.row}、列:{onecell.column}、値:{onecell.value}') | |
print(f'座標でセル位置を取得すると:{sheet.cell(row=4, column=2)}の値は{sheet.cell(row=4, column=2).value}') | |
print(f'セル位置は{onecell.coordinate}') | |
print('終了\n') | |
# 応用:1行おきにB列を取得 | |
print('● 開始') | |
print('応用:1行おきにB列を取得') | |
for i in range(1, 8, 2): | |
print(i, sheet.cell(row=i, column=2).value) | |
print('終了\n') | |
# シートスライス関係 | |
print('● 開始') | |
print(f'一部のシートを表示:{sheet["A1":"C3"]}') | |
print('1セルずつ抜き出してvalueを表示') | |
for i in sheet['A1':'C3']: | |
for j in i: | |
print(j.value) | |
print('=== end of row ===') | |
print('終了\n') | |
# 列一覧関係 | |
print('● 開始') | |
print(f'列一覧:{list(sheet.columns)[1]}') | |
print('列全体のvalueを表示') | |
for i in list(sheet.columns)[1]: | |
print(i.value) | |
print('終了\n') | |
# 行一覧関係 | |
print('● 開始') | |
print(f'行一覧:{list(sheet.rows)[1]}') | |
print('行全体のvalueを表示') | |
for i in list(sheet.rows)[1]: | |
print(i.value) | |
print('終了\n') | |
# 列の文字と番号を相互変換 | |
print('● 開始') | |
print(f'33列目の名前{get_column_letter(33)}') | |
print(f'最大列名{get_column_letter(sheet.max_column)}') | |
print(f'BCは{column_index_from_string("BC")}番目の列') | |
print('終了\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment