这里是要读取的数据,有数字和日期,用xlrd库读取的时候会发现,数字后面多了个".0",读取的日期变成了时间戳
def get_sheet1_data(excelDir, sheetName=None):
# 1- excel 放到磁盘----把它加载到内存里
workBook = xlrd.open_workbook(excelDir)
# 2- excel 指定表
sheet = workBook.sheet_by_name(sheetName)
example_row = sheet.nrows
data = []
for _ in range(1, example_row):
onerow = [sheet.row_values(_)[i] for i in range(len(sheet.row_values(1)))]
data.append(onerow)
return data
执行结果:
[['iosapp0', 123456.0, 44906.0, 1.0, '', ''], ['', 123456.0, 44906.0, 0.0, '', ''], ['iosapp0', '', 44906.0, 0.0, '', ''], ['iosapp00', 123456.0, 44906.0, 0.0, '', '']]
这当然不是我们想要的结果:因此需要优化代码
def get_sheet1_data(excelDir, sheetName=None):
# 1- excel 放到磁盘----把它加载到内存里
workBook = xlrd.open_workbook(excelDir)
# 2- excel 指定表
sheet = workBook.sheet_by_name(sheetName)
example_row = sheet.nrows
data = []
for eachrow in range(1, example_row):
onerow = []
for eachcol in range(3):
ctype = sheet.cell(eachrow, eachcol).ctype
cell = sheet.cell_value(eachrow, eachcol)
if ctype == 2 and cell % 1 == 0.0: # ctype为2且为浮点
cell = int(cell) # 浮点转成整型
cell = str(cell) # 转成整型后再转成字符串,如果想要整型就去掉该行
elif ctype == 3:
date = datetime(*xldate_as_tuple(cell, 0))
cell = date.strftime('%Y/%m/%d %H:%M:%S')
elif ctype == 4:
cell = True if cell == 1 else False
onerow.append(cell)
data.append(onerow)
return data
[['iosapp0', '123456', '2022/12/11 00:00:00'], ['', '123456', '2022/12/11 00:00:00'], ['iosapp0', '', '2022/12/11 00:00:00'], ['iosapp00', '123456', '2022/12/11 00:00:00']]