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:]

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM