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