使用sheet.iter_rows()生成器读取excel更加灵活。
# @Time: 2022/10/20 21:42
# @Author: jike
# @File: handle_excel_by_iter_rows.py
import openpyxl
class HandleExcelByIterRows():
def __init__(self, sheetName, filePath=None):
if filePath is None:
self.filePath = "./testdata/testdata.xlsx"
else:
self.filePath = filePath
self.sheetName = sheetName
def read_data_from_excel(self):
wbk = openpyxl.load_workbook(self.filePath)
sheet = wbk[self.sheetName]
# 通过生成器读取excel 每行数据
# 也可以指定从某行~某行,某列~某列读取
excel_datas = list(sheet.iter_rows(values_only=True))
# print(excel_datas)
# 获取第一行作为key
head_list = excel_datas[0]
# 获取隔行的value
rows_datas = excel_datas[1:]
testcases = []
# 通过 zip() 函数,将每行value值与key一一对应组成字典
for one_row in rows_datas:
testcase = dict(zip(head_list, one_row))
testcases.append(testcase)
return testcases
if __name__ == '__main__':
print(HandleExcelByIterRows("User_Service_Java").read_data_from_excel())
pass