Python-DDT-01
课题
数据驱动测试
Python接口自动化-DDT-Excel-01
环境
1.pycharm,python3
2.安装xlrd:pip install xlrd
Excel操作案例
import xlrd
# 从Excel中获取数据
def GetListFromExcelData(excelname, sheetname):
# 打开Excel文件方式
Exc = xlrd.open_workbook(excelname)
# 选择其实中一个sheet
sheet1 = Exc.sheet_by_name(sheetname)
# 常用方法使用
# print('第一行数据:', sheet1.row_values(0))
# print('第一行,第一列数据:', sheet1.row_values(0)[0])
datelist = []
for i in range(1, sheet1.nrows):
for j in range(0, sheet1.ncols):
values = sheet1.row_values(i)[j]
datelist.append(values)
return datelist
datas = GetListFromExcelData('test01.xls', 'Sheet1')
print(datas)
def GetDictFromExcelData(excelname, sheetname):
Exc = xlrd.open_workbook(excelname)
sheet1 = Exc.sheet_by_name(sheetname)
datelist = []
for i in range(1, sheet1.nrows):
datadict = {}
for j in range(0, sheet1.ncols):
# datadict[sheet1.row_values(0)[j]] 获取字段名-key,赋值为value
# 示例 dict['Age'] = 8
datadict[sheet1.row_values(0)[j]] = sheet1.row_values(i)[j]
datelist.append(datadict)
return datelist
datas = GetDictFromExcelData('test01.xls', 'Sheet1')
print(datas)
# 示例:获取第二个的用户名
print(GetDictFromExcelData('test01.xls', 'Sheet1')[1]['username'])
# 输出结果
# ['Mike', '123456', 'Bob', '147852', 'An', '147854']
# [{'username': 'Mike', 'password': '123456'}, {'username': 'Bob', 'password': '147852'}, {'username': 'An', 'password': '147854'}]
# Bob