1 # -*-coding:utf-8 -*-
2 # 在使用xlrd讀取excel的.xls類型文件時,讀取的數據默認為浮點型,包括對整數型/時間/布爾值...類型數據的讀取,
3 # 因此在按行或列的方式讀取sheet數據時進行數據類型轉換
4 import xlrd 5 read_book = xlrd.open_workbook(r'C:\Users\Administrator\Desktop\test.xls') # 打開文件

6 # 1.讀取sheet對象
7 work_sheet_index = read_book.sheet_by_index(0) # 通過sheet索引獲得sheet對象
8 # 2.獲取指定sheet基本信息
9 sheet_name = work_sheet_index.name # 獲取索引為0的sheet姓名
10 sheet_row = work_sheet_index.nrows # 獲取該sheet的總行數
11 sheet_col = work_sheet_index.ncols # 獲取該sheet的總列數
12 # 3.按行或列的方式獲得sheet數據
13 for i in range(sheet_row): 14 print(work_sheet_index.row_values(i)) # 每一行的數據用一個列表表示,但讀出的數據默認為浮點型
15

16 # 以下代碼是對用xlrd讀取excel數據時默認是浮點型數據的轉換代碼
17 import datetime 18 import numpy as np 19 list_cell = [] 20 # ②dict_key = []
21 for i in range(sheet_row): 22 list_during = [] 23 # ①list_during = {}
24 for j in range(sheet_col): 25 cell_type = work_sheet_index.cell(i, j).ctype # 表格的數據類型
26 # 判斷python讀取的返回類型 0 --empty,1 --string, 2 --number(都是浮點), 3 --date, 4 --boolean, 5 --error
27 cell = work_sheet_index.cell_value(i, j) # 獲取單元格的值
28 if cell_type == 2 and cell % 1 == 0.0: 29 cell = int(cell) # 浮點轉成整型
30 elif cell_type == 3: 31 date = datetime.datetime(*xlrd.xldate_as_tuple(cell, 0)) # 第一個參數是要處理的單元格,第二個參數是時間基准0代表以1900-01-01為基准
32 cell = date.strftime('%Y/%m/%d') # 轉為字符串
33 elif cell_type == 4: 34 if cell == 1: 35 cell = True 36 else: 37 cell = False 38 """
39 若想變成key對應value,即大列表里是字典且每個key列名都對應cell單元格值 40 ①list_during={}變成空字典 41 ②增加dict_key = [] 42 ③將i=0的第一行設為key值並增加相應的if條件 43 ④最后將字典append列表中時也增加if條件,第一個字典即列名不單獨作為一個元素放到列表中

44 """
45 # ③if i == 0:
46 # dict_key.append(cell) # 第一行為列名即為key
47 # else:
48 # list_during[dict_key[j]] = cell
49 list_during.append(cell) 50 # ④if i == 0:
51 # del list_during
52 # else:
53 # list_cell.append(list_during)
54 list_cell.append(list_during) 55
56 print(np.array(list_cell)) # 直接使用np.array()進行列表換行
