Excelを読み込んで2次元リストにする(python)
色々作業をする時にExcelを読み込む必要があるケースが多いです。一括して読み込んでおくライブラリがあれば便利です。
- 環境はanaconda3。
- 2次元リストは全て文字列で、シート名をキーとした辞書型で返却する。
Dict[str,List[List[str]]] - Excelのセルの表示形式は「文字列」前提とします。
from typing import List,Dict
import xlrd
import os.path
from datetime import datetime,timedelta
def book_dict_ary(xl_path:str) -> Dict[str,List[List[str]]]:
"""
xlsxファイルをシート名をキーにした2次元リストを作成する。
Parameters
----------
xl_path : str
xlsxファイルのパス
xlsxファイルの表示形式は"文字列"限定
Returns
-------
book_dict : Dict[str,List[List[str]]]
シート名をキーとしたセルの2次元リストs
セルはすべてstr型
"""
# 引数チェック
if xl_path == None:
raise Exception('引数不正:None')
if not os.path.isfile(xl_path):
raise FileNotFoundError('ファイルが存在しない:' + xl_path)
# bookを開く
book = xlrd.open_workbook(xl_path)
# 辞書作成
return {sheet_name: sheet_cells_ary(book.sheet_by_name(sheet_name)) for sheet_name in book.sheet_names()}
def sheet_cells_ary(sheet:xlrd.sheet) -> List[List[str]]:
"""
引数に指定されたシートを2次元配リストにする。
Parameters
----------
sheet : xlrd.sheet
2次元リストにするシート。
Returns
-------
cells : List[List[str]]
2次元リスト
"""
return [[cell.value for cell in rows] for rows in sheet.get_rows()]
def _cell_value_to_str(cell:xlrd.sheet.Cell) -> str:
if cell == None or cell.ctype == xlrd.XL_CELL_EMPTY or cell.ctype == xlrd.XL_CELL_ERROR or cell.ctype == xlrd.XL_CELL_BLANK:
return ""
elif cell.ctype == xlrd.XL_CELL_TEXT:
return cell.value
elif cell.ctype == xlrd.XL_CELL_NUMBER or cell.ctype == xlrd.XL_CELL_BOOLEAN:
return str(cell.value)
elif cell.ctype == xlrd.XL_CELL_DATE:
return str(datetime(1899,12,30) + timedelta(days=cell.value))
if __name__ == "__main__":
tmp = book_dict_ary('sample.xlsx')
print(tmp)