excel の帳票を台帳にする
一件一様の excel でできた帳票を台帳にするという作業が結構あると思います。
今回は、xls ファイルを csv 形式で出力してみたいと思います。
カレントディレクトリの *-数字4桁.xls から、sample_report.csv へ出力します。
適当に改変して使ってみてください。
generate_report.py
#!/usr/bin/python3
# encoding: utf-8
import xlrd
import glob
import datetime
import csv
import sys
import re
# 数字なら datetime 型の変数にして返す
# 数字でなければ、そのまま返す
def exceldate(v):
if isinstance(v, int):
return datetime.date(1899,12,31) + datetime.timedelta(days=v)
else:
return v
# rev. を取り除く
def norev(v):
return re.sub(r’rev.’, ”, v)
def main():
# ファイルをオープン
with open(‘sample_report.csv’, ‘w’, newline=”) as csvfile:
writer = csv.writer(csvfile) # csv として書き出すため writer を作る
# カレントディレクトリにある末尾が – 数字4桁.xls のファイルを
# 一覧にする
files = glob.glob(‘*-[0-9][0-9][0-9][0-9].xls’)
for f in files:
wb = xlrd.open_workbook(filename=f) # ワークブック
ws = wb.sheet_by_name(‘帳票’) # ワークブックの ‘帳票’ というシート
# csv として出力
writer.writerow(
[int(ws.cell_value(0,0)),
ws.cell_value(0,1),
exceldate(ws.cell_value(0,2)),
norev(ws.cell_value(0,3))])
if __name__ == “__main__”:
main()
xlsx 形式のファイルの場合は、openpyxl というライブラリがあります。
https://openpyxl.readthedocs.org/en/2.3.3/#sample-code
などをご参考に。