openpyxl とは
openpyxl は Python で *.xlsx を読み書きするためのライブラリ。
A Python library to read/write Excel 2010 xlsx/xlsm files
https://openpyxl.readthedocs.org/en/default/
単独で使ってもあまり面白くないが、SSH ログイン先の構成情報を拾ってきて Excel のパラメータシートまで自動生成できると嬉しい人が居るかもしれないので、少しだけ試してみた。
コードを書いてみる
使えそうな機能を一つずつ試してみて、出来上がったサンプルコードがこちら。
import ssh
from openpyxl import Workbook
from openpyxl.styles.borders import Side, Border
from openpyxl.styles import Style, PatternFill
hostname = 'foo.bar.com'
username = 'root'
password = 'XXXXXXXX'
port = 22
client = ssh.SSHClient()
client.set_missing_host_key_policy(ssh.AutoAddPolicy())
client.connect(hostname, username = username, password = password, port = port)
stdin, stdout, stderr = client.exec_command('rpm -qa --queryformat="%{NAME},%{VERSION},%{RELEASE},%{ARCH},%{GROUP}\n" | sort')
wb = Workbook()
ws = wb.active
ws.append(['Name', 'Version', 'Release', 'Architecture', 'Group'])
for line in stdout.read().split('\n'):
ws.append(list(line.split(',')))
thin_border = Border(left = Side(style = 'thin'),
right = Side(style = 'thin'),
top = Side(style = 'thin'),
bottom = Side(style = 'thin'))
my_style = Style(border = thin_border)
for _row in ws.iter_rows('A1:E' + str(ws.max_row)):
for _cell in _row:
_cell.style = my_style
lightblueFill = PatternFill(start_color = '0000FFFF',
end_color = '0000FFFF',
fill_type = 'solid')
for _row in ws.iter_rows('A1:E1'):
for _cell in _row:
_cell.fill = lightblueFill
ws.column_dimensions['A'].width = 45
ws.column_dimensions['B'].width = 15
ws.column_dimensions['C'].width = 28
ws.column_dimensions['E'].width = 30
wb.save("output.xlsx")
openpyxl は内部的に Excel の行をリストとして扱っているので、ここでは SSH ログイン先で実行した rpm -qa … | sort の実行結果 (stdout) を一行ずつ読み込み、カラム単位に split したものをリストに変換して Workbook クラスのワークシート ws に append していけばよい。
セルに罫線をかけたり、色を指定したり、あるいは列の幅を変えるようなことも Styles モジュールで指定することが可能だ。
生成された Excel ファイル
上記のスクリプトを実行して出来上がったのが以下の Excel ファイル。
ファイル生成後の人為的な編集作業はもちろん行なっていない。
Python で使いやすいライブラリがあれば、数十行のコードでこれだけのことが簡単に出来るのでとても便利。
環境: Python 2.7.9 + openpyxl 2.3.1 にて確認。