python读写Excel

  写自动化测试用例的时候须要考虑将 测试数据 和 代码 分离,代码作一层分装,测试数据作统一管理,方便往后维护。这里介绍下测试数据存储在excel,由运行脚本读取的思路。python

 

python能够经过 xlrd(读) 和 xlwt(写) 这两个库来实现对Excel的操做。测试

 

1、xlrd 读取Excel内容

 举例我要获取以下表格的信息this

 

 1.打开excel表格spa

readbook = xlrd.open_workbook('D:\\automation--interface\\data\\testdata.xls')

 2.获取表格中全部sheetexcel

sheets = readbook.sheet_names()         #返回全部sheet,<class 'list'>:['Sheet1', 'Sheet3', 'Sheet2']

 3.选择某个sheetcode

sheet = readbook.sheet_by_index(0)                 #按以索引方式选中,索引从0开始
sheet = readbook.sheet_by_name('Sheet1')           #按name的方式选中

 4.获取表格的 行 和 列blog

nrows = sheet.nrows           #返回行:3
ncols = sheet.ncols           #返回列:2

 5.获取表格具体内容索引

rows = sheet.row_values(1)          #返回第2行,<class 'list'>: ['小米', 5.0]
cols = sheet.col_values(1)          #返回第2列,<class 'list'>: ['年龄', 5.0, 7.0]
lng = sheet.cell(1,1).value         #返回坐标(1,1)的数据:5.0

 

2、xlwt 写入Excel

 1.打开excel并添加一个sheet字符串

writebook = xlwt.Workbook()                #打开excel
test= writebook.add_sheet('test')          #添加一个名字叫test的sheet

 2.写入excelit

test.write(0,1,'this is a test')           #第0行第1列写入字符串'this is a test'

 3.保存

writebook.save('testdata.xls')             #必定要保存为xls,后缀是xlsx的文件打不开

 

 

 下面贴一段自动化测试过程当中根据参数名读取excel的代码:

import xlrd

class Readexcel(object):
    def __init__(self,filepath,parameter):
        self.filepath = filepath
        self.parameter = parameter

    def read(self):
        # 打开excel表格
        readbook = xlrd.open_workbook(self.filepath)
        sheet = readbook.sheet_by_name('Sheet1')

        # 查询须要的参数在第几列
        nrow = sheet.row_values(0)
        ncol_num = nrow.index(self.parameter)

        # 获取这一整列参数的values
        ncols = sheet.col_values(ncol_num)

        return ncols[1:]
相关文章
相关标签/搜索