-- CODING: UTF-8 --
@Time : 2022-09-26 15:25
@File : handle_excel
** 封装读取excel**
from openpyxl import load_workbook
import os
import json
from Common.handle_path import datas_dir #调用封装的路径方法
class HandleExcel:
def __init__(self, file_path, sheet_name):
self.wb = load_workbook(file_path)
self.sh = self.wb[sheet_name]
def read_titles(self):
titles = []
for item in list(self.sh.rows)[0]: # 遍历第1行当中每一列
titles.append(item.value)
return titles
def read_all_datas(self):
all_datas = [] # 将获取的数据放在列表
titles = self.read_titles()
for item in list(self.sh.rows)[1:]:
values = []
for val in item: # 获取每一行中的值
values.append(val.value) # 将value追加到一个列表
# print(values)
res = dict(zip(titles, values)) # 将获取的titles 和 values 打包成字典
# res["request_data"] = json.loads(res["request_data"]) #使用json库将json字符串转为字典
all_datas.append(res)
return all_datas
def close_file(self):
self.wb.close()
if __name__ == '__main__':
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "api_cases.xlsx")
file_path = os.path.join(datas_dir, "api_cases.xlsx") # 处理路径
exc = HandleExcel(file_path, "注册")
cases = exc.read_all_datas()
# print(cases)
for case in cases:
print(case)
标签:__,openpyxl,self,测试数据,titles,file,path,datas,读取
From: https://www.cnblogs.com/qiu1219/p/16731213.html