1. 程式人生 > >python之xlrd和xlwt模組讀寫excel使用詳解

python之xlrd和xlwt模組讀寫excel使用詳解

一、xlrd模組和xlwt模組是什麼
      xlrd模組是python第三方工具包,用於讀取excel中的資料;
      xlwt模組是python第三方工具包,用於往excel中寫入資料;


二、xlrd模組和xlwt模組的安裝

pip install xlrd
pip install xlwt

 

三、Excel表格結構如下:

 

 

四、使用xlrd模組讀取excel檔案

#讀取excel資料
    def read_excel(self,excel_path,sheet_name):
        xls = xlrd.open_workbook(excel_path,formatting_info=True)    # 先開啟已存在的表,formatting_info=True表示保留原表格的樣式
        sheet = xls.sheet_by_name(sheet_name)   # 通過sheet名稱獲得sheet物件
        dataList = []
        for rows in range(1,sheet.nrows):#迴圈行
            tempList = []
            for cols in range(0,sheet.ncols-2):#迴圈列,因為最後兩列是寫入結果的所以減2
                if cols==0:#判斷如果是第一列則直接設定行數。
                    tempList.append(rows)
                else:
                    tempList.append(sheet.cell_value(rows,cols))
            dataList.append(tempList)
        return dataList

read_excel方法引數說明:

excel_path引數為excel檔案的路徑,

sheet_name引數excel檔案中的sheet名稱。

 

五、使用xlrt模組向excel檔案中寫入資料

#向excel中寫入資料
    def write_excel(self,excel_path,sheet_name,rows,cols,value):
        #獲得當前系統時間
        current_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        # 開啟已存在的表,formatting_info=True表示保留原表格的樣式
        book = xlrd.open_workbook(excel_path,formatting_info=True)
        wb = copy(book)  # 複製excel
        sheet = wb.get_sheet(sheet_name)  #通過sheet名稱獲得sheet物件
        if value == 'fail':
            sheet.write(rows,cols,value,style=xlwt.easyxf('pattern: pattern solid,fore_colour red;'))     # 引用樣式
        elif value == 'ignore':
            sheet.write(rows,cols,value,style=xlwt.easyxf('pattern: pattern solid,fore_colour yellow;'))  # 引用樣式
        else:
            sheet.write(rows,cols,value)
        #設定時間列的寬度和值
        sheet.col(cols-1).width = 5000
        sheet.write(rows,cols-1,current_time)
        #儲存
        wb.save(excel_path)

read_excel方法引數說明:

excel_path引數為excel檔案的路徑,

sheet_name引數excel檔案中的sheet名稱。

rows引數把內容寫入到第幾行

cols引數表示把內容寫入到第幾列

value引數表示寫入的內容

 

六、執行程式碼如下:

if __name__ == '__main__':
    eu = ExcelUtil()
    #print(eu.read_excel(get_project_path()+"data/testdata.xls","查詢火車票"))
    eu.write_excel(get_project_path()+"data/testdata.xls","查詢火車票",1,6,"pass")
    eu.write_excel(get_project_path()+"data/testdata.xls","查詢火車票",2,6,"ignore")
    eu.write_excel(get_project_path()+"data/testdata.xls","查詢火車票",3,6,"fail")

  

七、獨行踽近,眾行致遠!
如果你覺得此文對你有幫助,如果你對此文有任何疑問,如果你對軟體測試、介面測試、自動化測試、面試經驗交流感興趣都可以加入軟體測試技術群:695458161,群裡發放的免費資料都是筆者十多年測試生涯的精華。還有同行一起交流