excel数据如下:
读取excel
# 读取excel文件
excel_data = xlrd.open_workbook(excel_path)
# 获取第一个sheet页
sheet = excel_data.sheet_by_index(0)
# 读取数据
for i in range(0, rows):
for j in range(0, cols):
print(sheet.cell(i,j).value)
打印结果
20200302.0
18560726646.0
43888.0
这里把整型数字和日期格式的数据都打印错了,不是我们想要的结果
解决格式问题
# 解决整型和日期型的格式问题
def format_excel(i,j):
# 表格的数据类型
# ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
ctype = sheet.cell(i, j).ctype
cell = sheet.cell_value(i, j)
if ctype == 2 and cell % 1 == 0: # 如果是整形
cell = int(cell)
elif ctype == 3:
# 转成datetime对象
cell = xldate_as_datetime(cell, 0).strftime('%Y/%m/%d')
return cell
- 这样,再读取excel就格式就不会乱了
for i in range(0, rows):
for j in range(0, cols):
print(sheet.cell(i,j).value)
- 打印结果
20200302
18560726646
2020/02/27