zoukankan      html  css  js  c++  java
  • python读写Excel

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

    python可以通过 xlrd(读) 和 xlwt(写) 这两个库来实现对Excel的操作。

    一、xlrd 读取Excel内容

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

     1.打开excel表格

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

     2.获取表格中所有sheet

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

     3.选择某个sheet

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

     4.获取表格的 行 和 列

    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

    二、xlwt 写入Excel

     1.打开excel并添加一个sheet

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

     2.写入excel

    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:]
     
  • 相关阅读:
    2.4 Image Sampling and Quantization
    3.3 Histogram Processing
    2.6 Basic Mathematical Tools
    3.1 Background
    2.5 Some Basic Realtionship Between Pixels
    3.4 Fundamentals of Spatial Filtering
    3.5 Smoothing(Lowpass)Spatial Filters
    pytorch和tensorflow安装
    池化层
    tensorboard之图可视化
  • 原文地址:https://www.cnblogs.com/shenh/p/10382679.html
Copyright © 2011-2022 走看看