1.引入openpyxl库

安装openpyxl库:pip install openpyxl

引入openpyxl库:from openpyxl import load_worbook

2.代码实现

from openpyxl import load_workbook#打开Excelwb = 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.代码封装

testdemo.xlsx

代码

#引入仓库from openpyxl import load_workbookclass DoExcel():    def __init__(self,file,sheet):        self.file=file        self.sheet=sheet    def return_excel_value(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(2,sheet_content.max_column+1):                data_dict["method"]=sheet_content.cell(n,2).value                data_dict["url"] = sheet_content.cell(n, 3).value                data_dict["data"] = eval(sheet_content.cell(n, 4).value)#eval()将数据类型还原                data_dict["expect"] = sheet_content.cell(n, 5).value            data_list.append(data_dict)#将字典存储到list        return data_listif __name__ == '__main__':    data_list = DoExcel("C:\\Users\\Administrator\\Desktop\\testdemo.xlsx","s1").return_excel_value()    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'}]Process finished with exit code 0