pytest参数化实现DDT:读取excel文件

读取excel文件:

  1. 首先安装xlrd:使用命令pip install xlrd==1.2.0
  2. 在使用时,导入xlrd
  3. xlrd.open_workbook(filename)方法打开一个excel文件,获取到一个工作簿对象wb
  4. wb.sheet_by_index()获取sheet对象,通过索引的方法,即索引0代表sheet1
  5. sheet.nrows和sheet.ncols获取行和列
  6. 使用for循环获取数据
import pytest
import xlrd

def get_data():
    filename = 'test.xlsx'
    wb = xlrd.open_workbook(filename)
    sheet = wb.sheet_by_index(0)
    rows = sheet.nrows
    print(rows)
    cols = sheet.ncols
    print(cols)
    lst = []
    for row in range(rows):
        for col in range(cols):
            cell_data = sheet.cell_value(row, col)
            lst.append(cell_data)

    return lst
@pytest.mark.parametrize('name', get_data())
def test1(name):
    print(name)

if __name__ == '__main__':
    pytest.main(['-sv', 'test_excel.py'])

test.xlsx的数据如下:
在这里插入图片描述
代码结果输出:

plugins: allure-pytest-2.9.41, dependency-0.5.1
collecting ... 1
3
collected 3 items

test_excel.py::test1[lily] lily
PASSED
test_excel.py::test1[bob] bob
PASSED
test_excel.py::test1[rose] rose
PASSED

============================== 3 passed in 0.04s ==============================

在安装xlrd的过程中需要注意的问题是,如果使用pip install xlrd,运行上述代码会报:xlrd.biffh.XLRDError: Excel xlsx file; not supported。

原因在于pip install xlrd指定的安装版本是2.0.1,而在xlrd官网: https://pypi.org/project/xlrd/#description 有提到:This library will no longer read anything other than .xls files. For alternatives that read newer file formats, please see http://www.python-excel.org/. ,xlrd从2.X版本开始只支持.xls格式的EXCEL文件,不支持其它的。
在这里插入图片描述
所以我们安装时需要指定版本:pip install xlrd==1.2.0。再运行正常输出。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远不要矫情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值