前言
在進(jìn)行軟件測試或設(shè)計(jì)自動(dòng)化測試框架時(shí)数苫,一個(gè)不可避免的過程就是: 參數(shù)化,在利用python進(jìn)行自動(dòng)化測試開發(fā)時(shí)辨液,通常會(huì)使用excel來做數(shù)據(jù)管理虐急,利用xlrd、xlwt開源包來讀寫excel滔迈。
環(huán)境安裝
首先在命令行下安裝xlrd止吁、xlwt
pip install xlrd
pip install xlwt
一個(gè)簡單的讀寫示例
讓我們先看一個(gè)簡單的excel讀寫示例,示例代碼功能燎悍,從表1中讀取數(shù)據(jù)敬惦。
excel數(shù)據(jù)表如圖所示
1、讀取代碼示例
#_*_ coding:utf-8 _*_
__author__ = '苦葉子'
import xlrd
if __name__ == '__main__':
? ?# excel文件全路徑
? ?xlPath = "C:\\Users\\lyy\\Desktop\\demo.xlsx"
? ?# 用于讀取excel
? ?xlBook = xlrd.open_workbook(xlPath)
? ?# 獲取excel工作簿數(shù)
? ?count = len(xlBook.sheets())
? ?print u"工作簿數(shù)為: ?", count
? ?# 獲取 表 數(shù)據(jù)的行列數(shù)
? ?table = xlBook.sheets()[0]
? ?nrows = table.nrows
? ?ncols = table.ncols
? ?print u"表數(shù)據(jù)行列為(%d, %d)" % (nrows, ncols)
? ?# 循環(huán)讀取數(shù)據(jù)
? ?for i in xrange(0, nrows):
? ? ? ?rowValues = table.row_values(i) # 按行讀取數(shù)據(jù)
? ? ? ?# 輸出讀取的數(shù)據(jù)
? ? ? ?for data in rowValues:
? ? ? ? ? ? print data, " ? ?",
? ? ? ?print ""
運(yùn)行效果如圖
2谈山、寫excel示例代碼
#_*_ coding:utf-8 _*_
__author__ = '苦葉子'
import xlwt
import random
if __name__ == '__main__':
? ?# 注意這里的excel文件的后綴是xls 如果是xlsx打開是會(huì)提示無效
? ?newPath = ?unicode("C:\\Users\\lyy\\Desktop\\demo_new.xls", "utf8")
? ?wtBook = xlwt.Workbook()
? ?# 新增一個(gè)sheet
? ?sheet = wtBook.add_sheet("sheet1", cell_overwrite_ok=True)
? ?# 寫入數(shù)據(jù)頭
? ?headList = [u'序號(hào)', u'數(shù)據(jù)1', u'數(shù)據(jù)2', u'數(shù)據(jù)3']
? ?rowIndex = 0
? ?col = 0
? ?# 循環(huán)寫
? ?for head in headList:
? ? ? ? sheet.write(rowIndex, col, head)
? ? ? ? col = ?col + 1
? ? # 寫入10行 0-99的隨機(jī)數(shù)據(jù)
? ? for index in xrange(1, 11):
? ? ? ? ? for col in xrange(1, 4):
? ? ? ? ? ? ? data = random.randint(0,99)
? ? ? ? ? ? ? sheet.write(index, 0, index) ?# 寫序號(hào)
? ? ? ? ? ? ? sheet.write(index, col, data) # 寫數(shù)據(jù)
? ? ? ? ?print u"寫第[%d]行數(shù)據(jù)" % index
? ? # 保存
? ?wtBook.save(newPath)
運(yùn)行結(jié)果如圖
結(jié)束語
這里只是簡單的對xlrd俄删、xlwt模塊的應(yīng)用演示,對于實(shí)際做自動(dòng)化測試過程中奏路,需要封裝一個(gè)通用的excel解析類畴椰,以便提高復(fù)用性和降低維護(hù)成本。
在實(shí)際應(yīng)用中鸽粉,我們通常需要對表格進(jìn)行合并斜脂、樣式設(shè)置等等系列動(dòng)作,請參考官方文檔触机,進(jìn)行更深入的學(xué)習(xí)研究
python excel官網(wǎng): http://www.python-excel.org/