cases.xlsx:
import openpyxl
class ReadExcel(object):
def __init__(self,filename,sheet_name):
'''
:param filename: 文件名 str
:param sheet_name: sheet名 str
'''
self.wb = openpyxl.load_workbook(filename)
self.sh = self.wb[sheet_name]
def read_case_line(self):
'''
读取数据,存入列表中
:return: list
'''
# 按行读取数据,转化为列表
case_rows = list(self.sh.rows)
print("按行读取数据:",case_rows)
# 获取表头
titles = []
for title in case_rows[0]:
titles.append(title.value)
# print("获取表头:",titles)
# 存贮用例的空列表
cases = []
for case in case_rows[1:]:
# print("查看列表1:",case)
# 获取第一条测试用例数据
data = []
for cell in case:
data.append(cell.value)
'''
判断单元格是否为字符串,
如果是,则用eval()
否,则不用eval()
'''
if isinstance(cell.value,str):
data.append(eval(cell.value))
else:
data.append(cell.value)
# 将数据存放到cases中
# 将该条数据和表头进行打包组合 dict(list(zip(titles,cases))))
cases_data = dict(list(zip(titles,data)))
cases.append(cases_data)
return cases
if __name__ == '__main__':
r = ReadExcel("D:\TestSoftware\PyCharm\PyCharmProject\Excel\data\cases.xlsx","user_login")
ds = r.read_case_line()
for d in ds:
print(d)
输出:
D:\TestSoftware\Anaconda3\python.exe D:/TestSoftware/PyCharm/PyCharmProject/Excel/case/demo2.py
按行读取数据: [(<Cell 'user_login'.A1>, <Cell 'user_login'.B1>, <Cell 'user_login'.C1>), (<Cell 'user_login'.A2>, <Cell 'user_login'.B2>, <Cell 'user_login'.C2>), (<Cell 'user_login'.A3>, <Cell 'user_login'.B3>, <Cell 'user_login'.C3>), (<Cell 'user_login'.A4>, <Cell 'user_login'.B4>, <Cell 'user_login'.C4>), (<Cell 'user_login'.A5>, <Cell 'user_login'.B5>, <Cell 'user_login'.C5>), (<Cell 'user_login'.A6>, <Cell 'user_login'.B6>, <Cell 'user_login'.C6>), (<Cell 'user_login'.A7>, <Cell 'user_login'.B7>, <Cell 'user_login'.C7>), (<Cell 'user_login'.A8>, <Cell 'user_login'.B8>, <Cell 'user_login'.C8>), (<Cell 'user_login'.A9>, <Cell 'user_login'.B9>, <Cell 'user_login'.C9>)]
{'id': 1, 'excepted': 1, 'data': '{"code":0,"msg":"用户名已存在"}'}
{'id': 2, 'excepted': 2, 'data': '{"code":0,"msg":"l两次密码不一致"}'}
{'id': 3, 'excepted': 3, 'data': '{"code":1,"msg":"注册成功"}'}
{'id': 4, 'excepted': 4, 'data': '{"code":0,"msg":"账号和密码必须再6-18位之间"}'}
{'id': 5, 'excepted': 5, 'data': '{"code":0,"msg":"账号和密码必须再6-18位之间"}'}
{'id': 6, 'excepted': 6, 'data': '{"code":0,"msg":"账号和密码必须再6-18位之间"}'}
{'id': 7, 'excepted': 7, 'data': '{"code":0,"msg":"账号和密码必须再6-18位之间"}'}
{'id': 8, 'excepted': 8, 'data': '{"code":0,"msg":"账号和密码必须再6-18位之间"}'}
Process finished with exit code 0