"""读取excel封装"""
import xlrd
import os
class SheetTypeError(object):
pass
class ExcelReader(object):
def __init__(self,excel_file,sheet_by):
if os.path.exists(excel_file):
self.excel_file = excel_file
self.sheet_by = sheet_by
self._data = list()
else:
raise FileNotFoundError("文件不存在")
def data(self):
#打开文件
if not self._data:
workbook = xlrd.open_workbook(self.excel_file)
if type(self.sheet_by) not in [str,int]:
raise SheetTypeError("请输入Str , Int")
elif type(self.sheet_by) == str:
sheet = workbook.sheet_by_name(self.sheet_by)
elif type(self.sheet_by) == int:
sheet = workbook.sheet_by_index(self.sheet_by)
#读取sheet内容
#返回list,元素:字典
#格式[{"a":"a1","b":"b1"},{"a":"a2","b":"b2"}]
#1、获取首行的信息
title = sheet.row_values(0)
#2、遍历测试行,首行组成dict,放在list
for row in range(1,sheet.nrows):
col_value = sheet.row_values(row)
self._data.append(dict(zip(title,col_value)))
return self._data
if __name__ == '__main__':
test_data = ExcelReader("D:\\20\\Interface_Python\\Params\\test_data.xlsx",0)
a=test_data.data()
print(a)