python自动化读取excel数据,写入excel数据,xlrd、xlutils

在做自动化测试的过程中,经常会从excel中读取数据,用例执行完成后,把执行结果再写入对应的单元格中,下面通过python的第三方库xlrd,xlutils库来操作,下面写上详细的操作方法。

本次代码是ui自动化,功能为检索功能,读取excel中检索关键字,检索成功后,把命中结果、检索响应时间、检索数量写入对应的行单元格中

1、首页导入相关包、方法

import xlrd,xlutils
from xlutils.copy import copy

2、读取excel

#打开参数化excel,获取表中行数
exceldir = r"C:Users17533Desktoppkulaw_autodataweike_law_data.xls"#excel路径,可以写相对路径
excel = xlrd.open_workbook(exceldir) # 打开excel

law_sheet = excel.sheets()[0] # 获取第一个sheet表
pnfl_sheet = excel.sheets()[1] # 获取第二个sheet表

rows = law_sheet.nrows # 获取lar行数
cols = law_sheet.ncols # 获取lar列数

col = law_sheet.col_values(0)#获取第一列的内容

3、写入excel

old_excel = xlrd.open_workbook(exceldir, formatting_info=True)#先打开原excel
new_excel = copy(old_excel)#通过xlutils把原excel复制成为一个临时excel

#写入excel的方法
def write_execl(row,check_result_list,result_count,response_time):
test_law_sheet = new_excel.get_sheet(0)#读取复制的excel的第一个sheet

test_law_sheet.write(row,1,check_result_list)#写入检索结果,写入(row,1)单元格
test_law_sheet.write(row,2, result_count)#写入检索结果总数量,写入(row,2)单元格
test_law_sheet.write(row,3, response_time) # 写入检索时间,写入(row,3)单元格

#对最后写入执行结果的excel保存操作,必须操作
new_excel.save(r"C:Users17533Desktoppkulaw_autodataweike_law_title_data_new.xls")

4、用例部分
class TestSearchTitle():

def test_search_title(self,browser):
"""
     搜索
"""

  search.fagui.click()
EleWait.ele_wait(search.select_title) # 直到元素出现
   sleep(3)
row = 1#定义此变量,为了后续写入excel某行数据使用
    #以下部分为从excel中读取的第一列内容进行循环调用
    for i in col[1:rows]:
  search.search_box.send_keys(Keys.CONTROL, 'a')
  search.search_box.send_keys(i)
  search.new_check.click()
  starttime=datetime.datetime.now()#开始时间
   sleep(0.2)
 a = 1
       while not search.result:
  sleep(0.2)
  a= a+1
         if a == 10:
break
      endtime=datetime.datetime.now()#结束时间
   response_time = str(endtime - starttime) # 检索总时长
   sleep(2)
check_result_list = []
for i in search.check_result:
  check_result_list.append(i.text)#追加命中结果

   if search.result_count:
  law_count = str(search.result_count.text)#抓取检索数量
  else:
  law_count = 0

write_execl(row,check_result_list,law_count,response_time) #调用写入excel函数进行写入
row = row +1 #此变量作用为写入单元格中下一行使用

 5、中间可能出现的问题

在使用过程中出现过一些报错,主要是因为xlrd的版本为2.1.0,读取xls文件时出现报错,后来把xlrd版本降为1.2.0就解决了。

查看本地xlrd版本,命令:pip show xlrd

可以先卸载现xlrd,命令:pip uninstall xlrd

安装1.2.0版本xlrd, 命令:pip install xlrd==1.2.0


,写入(row,1)单元格
原文地址:https://www.cnblogs.com/banxiade/p/14642027.html