解決python讀取excel日期變爲數字,int變爲double的格式問題

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章