xlrdを使ってエクセルからデータを取得する
良く使うものと簡単かつ適当なサンプルを。
- open_workbook("excel_file_name")
引数に指定したエクセルを開く
- sheet_by_name("sheet_name")
引数に指定したシートをアクティブにする
- nrows
シート内の行を取得する。range()と合わせて使う
- row_values(index)
引数の行のデータそのものをリストで取得
サンプル
import xlrd class ReadExcelFile(object): def __init__(self, original_file): self.original_file = original_file self.data = {} def read_excel(self): wb = xlrd.open_workbook(self.original_file) sheet = wb.sheet_by_name("sheet_name") for row_index in range(sheet.nrows): tmp_data = {} tmp_data = { sheet.row_values(row_index)[0]: { "A": "", "B": { "url": "", "result": "" }, "C": { "url": "", "result": "" }, "D": { "url": "", "result": "" }, } } tmp_data[sheet.row_values(row_index)[0]]["A"] = sheet.row_values(row_index)[1] tmp_data[sheet.row_values(row_index)[0]]["B"]["url"] = sheet.row_values(row_index)[2] tmp_data[sheet.row_values(row_index)[0]]["C"]["url"] = sheet.row_values(row_index)[3] tmp_data[sheet.row_values(row_index)[0]]["D"]["url"] = sheet.row_values(row_index)[4] self.data.update(tmp_data) return self.data def main(): ref = ReadExcelFile("excel_file")) result = ref.read_excel() # 何かまた処理 if __name__ == '__main__': main()