トモロログ

仕事や趣味でのメモや記録など

python から excel の操作

ライブラリ openpyxl を使用すればできた

https://openpyxl.readthedocs.io/en/default/index.html#

 

インストールはMac環境では

   
   pip install openpyxl

 

使用例

 

# coding: utf-8
import openpyxl

  wb = openpyxl.load_workbook(filename = 'sample.xlsx')
  sheet = wb['test']
  print sheet['A2'].value #セルA2の値

  cell_range = sheet['A1':'C10'] # Cells(A1:C10) の取得
  for cell in cell_range:
      print cell[0].value   # 列Aの各要素の値を出力
      # タプルで1列ごと取得 1行目なら (A1, B1, C1) となる Aの要素はインデックス0

#cell_range の中身
# (<Cell test.A1>, <Cell test.B1>, <Cell test.C1>)

# (<Cell test.A2>, <Cell test.B2>, <Cell test.C2>)
# (<Cell test.A3>, <Cell test.B3>, <Cell test.C3>)
# (<Cell test.A4>, <Cell test.B4>, <Cell test.C4>)
# (<Cell test.A5>, <Cell test.B5>, <Cell test.C5>)
# (<Cell test.A6>, <Cell test.B6>, <Cell test.C6>)
# (<Cell test.A7>, <Cell test.B7>, <Cell test.C7>)
# (<Cell test.A8>, <Cell test.B8>, <Cell test.C8>)
# (<Cell test.A9>, <Cell test.B9>, <Cell test.C9>)
# (<Cell test.A10>, <Cell test.B10>, <Cell test.C10>)


  sheet['A2'].value = 'てすと' # 値の代入 
  wb.save('sample.xlsx') # セーブ

 

基本的な読み書きは以上でだいたいいける。あとは都度サンプルを見ればよし。

VBAよりこっちの方が楽でよいし、データベースにアクセスしつつ値を入力できそうなので結構使えそう。