1.引入openpyxl库
安装openpyxl库:pip install openpyxl
引入openpyxl库:from openpyxl import load_worbook
2.代码实现
from openpyxl import load_workbook #打开Excel wb = load_workbook(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\testdemo.xlsx\") #定位表单 sheet = wb[\"s1\"] #定位单元格 行列值 print(\"获取最大行数:\",sheet.max_row) print(\"获取最大列数:\",sheet.max_column) # #遍历 test_list = []#列表 for a in range(2,sheet.max_row+1): test_dic = {} # 字典 for b in range(1,sheet.max_column+1): #获取指定单元格的值:sheet.cell(行,列).value #将获取到的数据添加到字典 test_dic[\"method\"]=sheet.cell(a,1).value test_dic[\"url\"]=sheet.cell(a,2).value test_dic[\"data\"]=eval(sheet.cell(a,3).value)#eavl() 把数据类转换成 原本数据类型 test_dic[\"expect\"]=sheet.cell(a,4).value test_list.append(test_dic)#将字典添加到列表 print(test_list)
输出:
最大行数: 3 最大列数: 4 [{\'method\': \'get\', \'url\': \'http://www.qabujiaban.com/user/login\', \'data\': {\'username\': \'uuuu222都44\', \'password\': \'WJHasb124*1\'}, \'expect\': \'0000\'}, {\'method\': \'get\', \'url\': \'http://www.qabujiaban.com/user/login\', \'data\': {\'username\': \'uuuu222都44\', \'password\': \'WJHasb124*1\'}, \'expect\': \'0000\'}]
3.代码封装
#引入仓库 from openpyxl import load_workbook class DoExcel(): def __init__(self,file,sheet): self.file=file self.sheet=sheet def get_excel_data(self): wb = load_workbook(self.file)#打开excel sheet_content = wb[self.sheet]#定位sheet工作博 data_list = []#列表用于存储测试数据 for n in range(2,sheet_content.max_row+1):#行,第一行是标题,所以从第二行开始 data_dict = {}#字典用于存储每组测试数据 for m in range(1,sheet_content.max_column+1): data_dict[\"method\"]=sheet_content.cell(n,1).value data_dict[\"url\"] = sheet_content.cell(n, 2).value data_dict[\"data\"] = eval(sheet_content.cell(n, 3).value)#eval()将数据类型还原 data_dict[\"expect\"] = sheet_content.cell(n, 4).value data_list.append(data_dict)#将字典存储到list return data_list if __name__ == \'__main__\': data_list = DoExcel(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\testdemo.xlsx\",\"s1\").get_excel_data() print(data_list) #输出:[{\'method\': \'post\', \'url\': \'http://www.qabujiaban.com/user/login\', \'data\': {\'username\': \'uuuu222都44\', \'password\': \'WJHasb124*1\'}, \'expect\': \'0000\'}, {\'method\': \'get\', \'url\': \'http://www.qabujiaban.com/user/login\', \'data\': {\'username\': \'uuuu222都44\', \'password\': \'WJHasb124*1\'}, \'expect\': \'0000\'}]
来源:https://www.cnblogs.com/QAbujiaban/p/16994805.html
本站部分图文来源于网络,如有侵权请联系删除。