基于Python的接口自動(dòng)化讀寫(xiě)excel文件的方法
引言
使用python進(jìn)行接口測(cè)試時(shí)常常需要接口用例測(cè)試數(shù)據(jù)、斷言接口功能、驗(yàn)證接口響應(yīng)狀態(tài)等,如果大量的接口測(cè)試用例腳本都將接口測(cè)試用例數(shù)據(jù)寫(xiě)在腳本文件中,這樣寫(xiě)出來(lái)整個(gè)接口測(cè)試用例腳本代碼將看起來(lái)很冗余和難以清晰的閱讀以及維護(hù),試想如果所有的接口測(cè)試數(shù)據(jù)都寫(xiě)在代碼中,接口參數(shù)或者測(cè)試數(shù)據(jù)需要修改,那不得每個(gè)代碼文件都要一一改動(dòng)?。因此,這種不高效的模式不是我們想要的。所以,在自動(dòng)化測(cè)試中就有個(gè)重要的思想:測(cè)試數(shù)據(jù)和測(cè)試腳本分離,也就是測(cè)試腳本只有一份,其中需要輸入數(shù)據(jù)的地方會(huì)用變量來(lái)代替,然后把測(cè)試輸入數(shù)據(jù)單獨(dú)放在一個(gè)文件中,這個(gè)存放測(cè)試輸入數(shù)據(jù)的文件,通常是表格的形式或者其他格式文件,如excel文件、json文件、xml文件、txt文本文件等等。在python進(jìn)行接口自動(dòng)化測(cè)試時(shí),為了方便管理和存儲(chǔ)測(cè)試用例數(shù)據(jù),一般將測(cè)試數(shù)據(jù)編寫(xiě)存儲(chǔ)在excel文件中,測(cè)試腳本通過(guò)讀取excel文件來(lái)實(shí)現(xiàn)測(cè)試數(shù)據(jù)加載,并運(yùn)行得出測(cè)試用例數(shù)據(jù)執(zhí)行的結(jié)果,并回寫(xiě)測(cè)試結(jié)果到excel文件中,這樣就實(shí)現(xiàn)了測(cè)試腳本和數(shù)據(jù)的分離。而python操作excel文件的讀寫(xiě),這里需要安裝并引入第三方模塊:xlrd和xlwt以及xlutils,xlrd為讀取excel模塊,xlwt為向excel寫(xiě)數(shù)據(jù)的模塊,xlutils可以復(fù)制excel并修改excel中的數(shù)據(jù)。下面就具體介紹xlrd和xlwt操作excel文件提供的通用方法和技巧,以及xlutils如何復(fù)制和修改excel,達(dá)到操作excel讀寫(xiě)的目的。
一、xlrd、xlwt以及xlutils安裝
1.使用pip安裝
pip install xlrd pip install xlwt pip install xlutils
2.在PyCharm中安裝
直接檢索需要安裝的模塊名稱即可,如xlrd:
二、xlrd操作excel文件的數(shù)據(jù)讀取
新建一個(gè)excel文件,文件名稱:excel_test.xlsx,文件編輯有兩個(gè)sheet表,內(nèi)容如下:
sheet1:
sheet2:
(1)打開(kāi)excel文件,獲取excel的sheet名
編輯如下代碼:
import xlrd file = xlrd.open_workbook("excel_test.xlsx") all_sheet = file.sheet_names() # 獲取所有的工作簿名 sheet_name1 = file.sheet_names()[0] # 通過(guò)sheet下標(biāo)獲取,第一個(gè)sheet下標(biāo)為0 sheet_name2 = file.sheet_by_index(0).name # 通過(guò)sheet索引獲取sheet名 print(all_sheet) print(sheet_name1) print(sheet_name2) ----------------------------------------- # 返回結(jié)果 ['員工信息表', 'api測(cè)試用例'] 員工信息表 員工信息表
(2)獲取sheet工作表頁(yè)的對(duì)象
代碼示例:
import xlrd file = xlrd.open_workbook("excel_test.xlsx") sheet_name1 = file.sheet_names()[0] sheet1_obj = file.sheet_by_name(sheet_name1) # 通過(guò)sheet名獲取sheet對(duì)象 sheet2_obj = file.sheet_by_index(1) # 通過(guò)sheet索引獲取sheet對(duì)象 print(sheet1_obj) print(sheet2_obj) ------------------------------------ # 返回結(jié)果 <xlrd.sheet.Sheet object at 0x0000000002AA09B0> <xlrd.sheet.Sheet object at 0x0000000002AA0978>
(3)獲取sheet工作表的行、列數(shù),整行、整列數(shù)據(jù),具體的單元格數(shù)據(jù)
代碼示例:
import xlrd file = xlrd.open_workbook("excel_test.xlsx") sheet = file.sheet_by_index(0) # 通過(guò)sheet索引獲取sheet對(duì)象 nrows = sheet.nrows # 獲取行數(shù) ncols = sheet.ncols # 獲取列數(shù) nrows_data = sheet.row_values(1) # 獲取第二行數(shù)據(jù),返回的是列表 ncols_data = sheet.col_values(0) # 獲取第一列數(shù)據(jù),返回的是列表 cell = sheet.cell(1,2) # 獲取單元格數(shù)據(jù),如第二行,第三列數(shù)據(jù) print(nrows) print(ncols) print(nrows_data) print(ncols_data) print(cell) ------------------------------- # 返回結(jié)果 6 5 ['王五', '男', 32883.0, 'java開(kāi)發(fā)工程師', 233.0] ['姓名', '王五', '李四', '張三', '小紅', '小明'] xldate:32883.0 # 這里日期數(shù)據(jù)直接返回成浮點(diǎn)數(shù)了
常見(jiàn)讀取excel不同數(shù)據(jù)類型的返回問(wèn)題,如讀取日期格式的數(shù)據(jù)
一般使用sheet.cell(rowx,colx)方法獲取單元格數(shù)據(jù),單元格數(shù)據(jù)類型判斷可以使用如下代碼:
print(sheet.cell(1,2).ctype) ------------ # 返回日期數(shù)據(jù)的結(jié)果 3
注:ctype : 0 empty,1 string, 2 number,3 date, 4 boolean, 5 error
讀取單元格日期數(shù)據(jù)為浮點(diǎn)數(shù)的處理方式:
代碼如下:
import xlrd from datetime import date file = xlrd.open_workbook("excel_test.xlsx") sheet = file.sheet_by_index(0) # 通過(guò)sheet索引獲取sheet對(duì)象 nrows_data = sheet.row_values(1) # 獲取第二行數(shù)據(jù),返回的是列表 ncols_data = sheet.col_values(0) # 獲取第一列數(shù)據(jù),返回的是列表 cell = sheet.cell(1,2) # 獲取單元格數(shù)據(jù),如第二行,第三列數(shù)據(jù),返回的是浮點(diǎn)數(shù) data_value = xlrd.xldate_as_tuple(sheet.cell_value(1,2) ,file.datemode) # xldate_as_tuple()方法得到日期數(shù)據(jù)年月日時(shí)分秒的值并返回為元組 datatime2 = date(*data_value[:3]).strftime('%Y/%m/%d') # 截取元組中的前三位,即年月日的值傳給data,并進(jìn)行時(shí)間格式化 print(cell) print(data_value) print(datatime2) ----------------------- # 返回結(jié)果 xldate:32883.0 (1990, 1, 10, 0, 0, 0) 1990/01/10
因此在讀取excel單元格數(shù)據(jù),如遇到是日期格式的數(shù)據(jù),可以加上如下代碼判斷并處理:
if (sheet.cell(row,col).ctype == 3): date_value = xlrd.xldate_as_tuple(sheet.cell_value(row,col),file.datemode) date_tmp = date(*date_value[:3]).strftime('%Y/%m/%d')
三、xlwt向excel文件寫(xiě)入數(shù)據(jù)
xlwt一般用于向excel文件寫(xiě)入數(shù)據(jù),簡(jiǎn)單示例如下:
import xlwt workbook = xlwt.Workbook(encoding = 'utf-8') # 創(chuàng)建工作簿 sheet = workbook.add_sheet('api_test') # 添加一個(gè)sheet data = sheet.write(0,0,'test') # 向第一行第一列寫(xiě)入數(shù)據(jù):test workbook.save('book.xlsx') # 保存到book.xlsx中
運(yùn)行完成后會(huì)在該py文件的同級(jí)目錄下生成一個(gè)book.xlsx的excel文件,并新增了api_test的sheet表名,第一行第一列寫(xiě)入數(shù)據(jù):test
向excel寫(xiě)入數(shù)據(jù)時(shí),可以設(shè)置單元格長(zhǎng)寬、單元格合并、寫(xiě)入時(shí)間格式數(shù)據(jù)以及添加超鏈接等
代碼示例:
import xlwt import datetime workbook = xlwt.Workbook(encoding = 'utf-8') # 創(chuàng)建工作簿 sheet = workbook.add_sheet('api_test') # 添加一個(gè)sheet data = sheet.write(4,0,'test') sheet.col(0).width = 5000 # 設(shè)置單元格寬度 style = xlwt.XFStyle() # 初始化表格樣式 style.num_format_str = 'M/D/YY' # 設(shè)置時(shí)間格式,如:M/D/YY sheet.write(5, 1, datetime.datetime.now(), style) # 寫(xiě)入時(shí)間格式數(shù)據(jù) # 合并多列和和并多行 # 表示合并的行數(shù)是:按行索引,從0行到第0行,按列索引從0列到第3列,合并后并寫(xiě)入數(shù)據(jù):test1 sheet.write_merge(0, 0, 0, 3, 'test1') # 表示合并的行數(shù)是:按行索引,從1行到第2行,按列索引從0列到第3列,合并后并寫(xiě)入數(shù)據(jù):test2 sheet.write_merge(1, 2, 0, 3, 'test2') # 向單元格添加超鏈接 sheet.write(6, 0, xlwt.Formula('HYPERLINK("https://www.baidu.com/";"baidu")')) workbook.save('book.xlsx') # 保存到book.xlsx中
運(yùn)行后輸出excel效果如下:
四、xlutils操作excel文件
(1)拷貝excel表格
xlutils模塊下的copy可以復(fù)制拷貝excel文件,代碼示例:
import xlrd from xlutils.copy import copy excel_file = xlrd.open_workbook("book.xlsx") new_file = copy(excel_file) # 拷貝文件對(duì)象 new_file.save("book1.xlsx") # 保存為excel文件
運(yùn)行以上代碼會(huì)在同級(jí)目錄下生成一個(gè)book1.xlsx的excel文件,該文件和book.xlsx一樣,只是文件名稱不一樣而已,也就是復(fù)制excel文件了
(2)修改excel文件內(nèi)容
除了copy為其他excel文件外,也可以直接copy文件修改后,保存為同名的文件,那修改的內(nèi)容將直接覆蓋原excel文件,達(dá)到修改的目的
示例:
import xlrd from xlutils.copy import copy excel_file = xlrd.open_workbook("book.xlsx") new_file = copy(excel_file) sheet = new_file.get_sheet(0) # 獲取表格的第一個(gè)sheet sheet.write(0,1,"測(cè)試") # 第一行第二列寫(xiě)入:測(cè)試 sheet.write(1,1,"測(cè)試1") # 第二行第二列寫(xiě)入:測(cè)試1 new_file.save("book.xlsx")
運(yùn)行后book.xlsx表會(huì)修改更新
五、封裝操作excel讀和寫(xiě)的類
通過(guò)上面介紹,基本具備使用xlrd、xlwt、xlutils模塊進(jìn)行excel文件數(shù)據(jù)讀取和向excel文件中寫(xiě)入數(shù)據(jù),在進(jìn)行接口測(cè)試時(shí),我們說(shuō)到需要:測(cè)試數(shù)據(jù)和測(cè)試腳本分離,后續(xù)的接口測(cè)試用例數(shù)據(jù),我們統(tǒng)一寫(xiě)入excel表格中,然后通過(guò)操作excel來(lái)讀取測(cè)試數(shù)據(jù)并將測(cè)試結(jié)果回填到excel中。因此,咱們需要對(duì)向excel讀取數(shù)據(jù)和向excel寫(xiě)入數(shù)據(jù)的操作進(jìn)行封裝。
我們操作上面的api測(cè)試用例這個(gè)sheet,封裝讀取excel數(shù)據(jù)的類,代碼示例:
from xlrd import open_workbook class Readexcel(): def excel_data_list(self, filename, sheetname): ''' :param filename: excel文件名稱 :param sheetname: excel中表格sheet名稱 :return: data_list ''' data_list = [] wb = open_workbook(filename) # 打開(kāi)excel sh = wb.sheet_by_name(sheetname) # 定位工作表 header = sh.row_values(0) # 獲取標(biāo)題行的數(shù)據(jù) for i in range(1, sh.nrows): # 跳過(guò)標(biāo)題行,從第二行開(kāi)始獲取數(shù)據(jù) col_datas = dict(zip(header, sh.row_values(i))) # 將每一行的數(shù)據(jù),組裝成字典 data_list.append(col_datas) # 將字典添加到列表中 ,列表嵌套字典,每個(gè)元素就是一個(gè)字典 return data_list if __name__ == '__main__': Readexcel()
上面代碼封裝了讀取excel數(shù)據(jù)的類,將每一行數(shù)據(jù)讀取出來(lái)組裝成字典并添加到列表中
實(shí)例化運(yùn)行:
data_list = Readexcel().excel_data_list('excel_test.xlsx','api測(cè)試用例') print(data_list) ----------------------- # 返回結(jié)果 [ {'module': '視頻安防', 'url': 'http://imp-t.tfgreenroad.com:18092/console_api/recep/tv/list', 'id': 1.0, 'params': '{ "queryMsg":"","regionCode":"","devtypeCode":"","online":"","offset":"","limit":1,"type":""}', 'method': 'get', 'actual_res': '', 'data': '', 'expect_res': '', 'test_res': '', 'case_name': '分頁(yè)查詢視頻安防設(shè)備列表', 'files': ''}, {'module': '平臺(tái)管理', 'url': 'http://imp-t.tfgreenroad.com:18092/console_api/manage/appsys/info', 'id': 2.0, 'params': '', 'method': 'post', 'actual_res': '', 'data': '{"appName": "hahh","appId": "34434343","appUrl": "http://12306.com","appCode": "89","remark":""}', 'expect_res': '{"code": 200,"errMsg": ""}', 'test_res': '', 'case_name': '應(yīng)用管理-單個(gè)應(yīng)用系統(tǒng)添加', 'files': ''}, {'module': '平臺(tái)管理', 'url': 'http://imp-t.tfgreenroad.com:18092/console_api/manage/appsys/info/upappid/89', 'id': 3.0, 'params': '', 'method': 'put', 'actual_res': '', 'data': '{"appId": "3232327676888"}', 'expect_res': '{"code": 200,"errMsg": ""}', 'test_res': '', 'case_name': '應(yīng)用管理-修改應(yīng)用appId', 'files': ''}, {'module': '平臺(tái)管理', 'url': 'http://imp-t.tfgreenroad.com:18092/console_api/manage/devtype/list', 'id': 4.0, 'params': '{ "queryMsg":"15002","offset":"","limit":""}', 'method': 'get', 'actual_res': '', 'data': '', 'expect_res': '', 'test_res': '', 'case_name': '設(shè)備分類-分頁(yè)獲取設(shè)備類型', 'files': ''} ]
封裝向excel寫(xiě)入數(shù)據(jù)的類,代碼示例:
from xlutils.copy import copy from xlrd import open_workbook class Write_excel(): def write_result(self, filename, row, col1,col2,actual_res, test_res,sheet_name): ''' :param filename: 文件名 :param row: 要寫(xiě)回的行 :param col1: 要寫(xiě)回的列 :param col2: 要寫(xiě)回的列 :param actual_res: 實(shí)際結(jié)果 :param test_res: 測(cè)試結(jié)果 :pass/failed :param sheet_name:指定的sheet表索引 :return: ''' old_workbook = open_workbook(filename) # 將已存在的excel拷貝進(jìn)新的excel new_workbook = copy(old_workbook) # 獲取sheet new_worksheet = new_workbook.get_sheet(sheet_name) # 第n個(gè)sheet,0表示第一個(gè)sheet # 寫(xiě)入數(shù)據(jù) new_worksheet.write(row, col1, actual_res) new_worksheet.write(row, col2, test_res) # 保存 new_workbook.save("book.xlsx") if __name__ == '__main__': Write_excel()
這樣我們就完成了讀寫(xiě)excel操作的封裝,后續(xù)接口測(cè)試數(shù)據(jù)的讀取和寫(xiě)入就依靠這兩個(gè)類了。
到此這篇關(guān)于基于Python的接口自動(dòng)化讀寫(xiě)excel文件的文章就介紹到這了,更多相關(guān)Python接口自動(dòng)化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 教你用Python代碼實(shí)現(xiàn)合并excel文件
- python里讀寫(xiě)excel等數(shù)據(jù)文件的6種常用方式(小結(jié))
- 如何用python合并多個(gè)excel文件
- 使用Python快速打開(kāi)一個(gè)百萬(wàn)行級(jí)別的超大Excel文件的方法
- 淺談Python xlwings 讀取Excel文件的正確姿勢(shì)
- Python3利用openpyxl讀寫(xiě)Excel文件的方法實(shí)例
- python excel和yaml文件的讀取封裝
- python基于openpyxl生成excel文件
- python合并多個(gè)excel文件的示例
- Python批量操作Excel文件詳解
相關(guān)文章
Python Matplotlib 基于networkx畫(huà)關(guān)系網(wǎng)絡(luò)圖
這篇文章主要介紹了Python Matplotlib 基于networkx畫(huà)關(guān)系網(wǎng)絡(luò)圖,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07pyqt5 QProgressBar清空進(jìn)度條的實(shí)例
今天小編就為大家分享一篇pyqt5 QProgressBar清空進(jìn)度條的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06利用python微信庫(kù)itchat實(shí)現(xiàn)微信自動(dòng)回復(fù)功能
最近發(fā)現(xiàn)了一個(gè)特別好玩的Python 微信庫(kù)itchat,可以實(shí)現(xiàn)自動(dòng)回復(fù)等多種功能,下面這篇文章主要給大家介紹了利用python微信庫(kù)itchat實(shí)現(xiàn)微信自動(dòng)回復(fù)功能的相關(guān)資料,需要的朋友可以參考學(xué)習(xí),下面來(lái)一起看看吧。2017-05-05python 默認(rèn)參數(shù)問(wèn)題的陷阱
本文給大家講述的是python 默認(rèn)參數(shù)問(wèn)題的陷阱,有需要的小伙伴可以參考下2016-02-02windows中python實(shí)現(xiàn)自動(dòng)化部署
本文主要介紹了windows中python實(shí)現(xiàn)自動(dòng)化部署,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08python使用writerows寫(xiě)csv文件產(chǎn)生多余空行的處理方法
這篇文章主要介紹了python使用writerows寫(xiě)csv文件產(chǎn)生多余空行的處理方法,需要的朋友可以參考下2019-08-08