使用openpyxl庫,“將用例資料(xlsx格式)轉化為內嵌字典的列表資料”的嘗試
阿新 • • 發佈:2021-03-16
用例資料內容格式如下:
嘗試1:sh.rows #所有行
import openpyxl class Excel(): def __init__(self,wb_path,sheet_name): self.wb_path = wb_path self.sheet_name =sheet_name def data(self): wb = openpyxl.load_workbook(self.wb_path) sh = wb[self.sheet_name] rows = list(sh.rows) #先把sheet中每行資料儲存為一個內嵌列表的列表 case1 =[] for row in rows: case2 =[] for cell in row: case2.append(cell.value) case1.append(case2) #在把內嵌列表的列表轉化為內嵌字典的列表,注意第一行資料是標題 total = [] for a in case1[1:]: total.append(dict(zip(case1[0],a))) return total a = Excel(r'C:\Users\dell\Desktop\123.xlsx','Sheet1').data() print(a) #拆分一下 import openpyxl class ExcelHandler(): def __init__(self, file_path, ): self.file_path = file_path def get_title(self, sheet_name): wb = openpyxl.load_workbook(self.file_path) sh = wb[sheet_name] row = list(sh[1]) title = [] for cell in row: title.append(cell.value) return title def get_data(self, sheet_name): ''' 用作資料驅動下的資料輸入 :param sheet_name: 一個sheet對應一個用例指令碼,整個excel檔案對應一個完整的專案 :return: 內建字典的列表,列表包含整個整個sheet的資料,一個字典對應一行測試資料 ''' wb = openpyxl.load_workbook(self.file_path) sh = wb[sheet_name] rows = list(sh.rows) total_data = [] for row in rows[1:]: row_data = [] for cell in row: row_data.append(cell.value) total_data.append(dict(zip(self.get_title(sheet_name), row_data))) return total_data
嘗試2:sh.max_row #最大行數
import openpyxl class Excel(): def __init__(self, wb_path, sheet_name): self.wb_path = wb_path self.sheet_name = sheet_name def data(self): wb = openpyxl.load_workbook(self.wb_path) sh = wb[self.sheet_name] max_row = sh.max_row total = [] for a in range(2, max_row + 1): case = dict( url=sh.cell(a, 1).value, data=sh.cell(a, 2).value, expected=sh.cell(a, 3).value ) total.append(case) return total a = Excel(r'C:\Users\dell\Desktop\123.xlsx', 'Sheet1').data() print(a)