pythonのopenpyxlモジュールを使ってエクセル操作【4時間目:もっとセル操作】

列の文字と番号を相互変換する

列はA,B,C,D,E。というようになっていると思います。これを番号に変換できるし、もしくは、番号を列記号に置き換えることもできます。相互変換を行うには

  • column_index_from_string() → 列記号から番号に変換
  • get_column_letter → 番号から列記号に変換

を使う必要があります。またポイントして

from openpyxl.utils import get_column_letter, column_index_from_string というimport構文を書きます。この構文は書籍と違う場合もあります。openpyxlモジュールが進化を続けているからです。以下にサンプルコードをのせておきます。

import openpyxl, os
from openpyxl.utils import get_column_letter, column_index_from_string
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
print(get_column_letter(sheet.max_column))#C
print(column_index_from_string('A'))#1

シートから複数の行と列を取得する

sheetをスライスするとtupleで表示されます。tupleは値の変更できないリストです。(スライスに関してはリストのスライスで検索)ポイントは1行ごとに順番で入っているということでしょうか。

import openpyxl, os
from openpyxl.utils import get_column_letter, column_index_from_string
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
print(tuple(sheet['A1':'C3']))
'''
((<Cell 'Sheet1'.A1>, <Cell 'Sheet1'.B1>, <Cell 'Sheet1'.C1>), 
 (<Cell 'Sheet1'.A2>, <Cell 'Sheet1'.B2>, <Cell 'Sheet1'.C2>), 
 (<Cell 'Sheet1'.A3>, <Cell 'Sheet1'.B3>, <Cell 'Sheet1'.C3>))
'''

forループで回すと各セルの値を表示できます。ポイントは外側のforループが行を、内側のforループが列を処理していることでしょうか。

for row_cell in sheet['A1':'C3']:
 for cell in row_cell:
 print(cell.coordinate, cell.value)
 print('-------')
'''
A1 2015-04-05 13:34:02
B1 Apples
C1 73
-------
A2 2015-04-05 03:41:23
B2 Cherries
C2 85
-------
A3 2015-04-06 12:46:51
B3 Pears
C3 14
-------
'''

次は「pythonのopenpyxlモジュールを使ってエクセル操作【5時間目:rows, columns】」です。