# -*- coding:utf-8 -*- # @Time : 2019-10-23 # @Author : carl_dj import xlrd from Interface_python3.public import config from Interface_python3.public.log import Log class ReadExcel(object): # 參數excel_path是文件的絕對路徑,sheet_name是表名 def __init__(self, excel_path, sheet_name="Sheet1"): self.data = xlrd.open_workbook(excel_path) # 根據路徑打開一個文件 self.table = self.data.sheet_by_name(sheet_name) # 根據表名打開表 self.keys = self.table.row_values(0) # 獲取第一行作爲字典的key值 self.rowNum = self.table.nrows # 獲取總行數 self.colNum = self.table.ncols # 獲取總列數 self.log = Log("讀取excel").get_logger() # 獲取整張表的數據(數據裝在列表中,列表的每個子元素是字典類型數據) def get_dict_data(self): if self.rowNum <= 1: self.log.error('xlsx表的總行數小於1') else: r = [] # 定義列表變量,把讀取的每行數據拼接到此列表中 for row in range(1, self.rowNum): # 對行進行循環讀取數據,從第二行開始 s = {} # 定義字典變量 s['rowNum'] = row + 1 # 存儲行數,從第二行開始讀,行數等於下標加1 values = self.table.row_values(row) # 獲取行的數據 for col in range(0, self.colNum): # 對列進行循環讀取數據 cell_value = values[col] if isinstance(cell_value, (int, float)): # 判斷讀取數據是否是整型或浮點型 cell_value = int(cell_value) # 是,數據轉換爲整數 s[self.keys[col]] = str(cell_value).strip() # 獲取到單元格數據(去掉頭尾空格)和key組成鍵對值 r.append(s) # 把獲取到行的數據裝入r列表中 return r # 返回整個表的數據 if __name__ == "__main__": file_path = config.test_data_path + 'test.xlsx' sheetName = "test" sheet = ReadExcel(file_path, sheetName) data = sheet.get_dict_data() print(data[0]['checkpoint']) print(type(data[0]['checkpoint'])) print(data)
接口自動化框架(Python)之 四,讀取exlce表格
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.