本文章來源於: https://www.cnblogs.com/insane-Mr-Li/p/9092619.html
那我就一下面積個問題對xlrd模塊進行學習一下:
1.什么是xlrd模塊?
2.為什么使用xlrd模塊?
3.怎樣使用xlrd模塊?
1.什么是xlrd模塊?
♦python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫。
今天就先來說一下xlrd模塊:
一、安裝xlrd模塊
♦ 到python官網下載http://pypi.python.org/pypi/xlrd模塊安裝,前提是已經安裝了python 環境。
♦或者在cmd窗口 pip install xlrd
二、使用介紹
♦ 0. empty(空的),1 string(text), 2 number, 3 date, 4 boolean, 5 error, 6 blank(空白表格)
import xlrd
data = xlrd.open_workbook(filename)#文件名以及路徑,如果路徑或者文件名有中文給前面加一個r拜師原生字符。
4、常用的函數
♦ excel中最重要的方法就是book和sheet的操作
table = data.sheets()[0] #通過索引順序獲取 table = data.sheet_by_index(sheet_indx)) #通過索引順序獲取 table = data.sheet_by_name(sheet_name)#通過名稱獲取 以上三個函數都會返回一個xlrd.sheet.Sheet()對象 names = data.sheet_names() #返回book中所有工作表的名字 data.sheet_loaded(sheet_name or indx) # 檢查某個sheet是否導入完畢
如:
nrows = table.nrows #獲取該sheet中的有效行數 table.row(rowx) #返回由該行中所有的單元格對象組成的列表 table.row_slice(rowx) #返回由該列中所有的單元格對象組成的列表 table.row_types(rowx, start_colx=0, end_colx=None) #返回由該行中所有單元格的數據類型組成的列表 table.row_values(rowx, start_colx=0, end_colx=None) #返回由該行中所有單元格的數據組成的列表 table.row_len(rowx) #返回該列的有效單元格長度
ncols = table.ncols #獲取列表的有效列數 table.col(colx, start_rowx=0, end_rowx=None) #返回由該列中所有的單元格對象組成的列表 table.col_slice(colx, start_rowx=0, end_rowx=None) #返回由該列中所有的單元格對象組成的列表 table.col_types(colx, start_rowx=0, end_rowx=None) #返回由該列中所有單元格的數據類型組成的列表 table.col_values(colx, start_rowx=0, end_rowx=None) #返回由該列中所有單元格的數據組成的列表
如:
table.cell(rowx,colx) #返回單元格對象 table.cell_type(rowx,colx) #返回單元格中的數據類型 table.cell_value(rowx,colx) #返回單元格中的數據 table.cell_xf_index(rowx, colx) # 暫時還沒有搞懂
♦單元格:單元格是表格中行與列的交叉部分,它是組成表格的最小單位,可拆分或者合並。單個數據的輸入和修改都是在單元格中進行的
如:
注意:注意作用域問題,之前獲取的sheet之后,都在獲取到這個sheet值后,在進行,行和列以及單元格的操作。
♦ python解決open()函數、xlrd.open_workbook()函數文件名包含中文,sheet名包含中文報錯的問題
問題現象:
♦1、使用open()函數、xlrd.open_workbook()函數打開文件,文件名若包含中文,會報錯找不到這個文件或目錄。
♦2、獲取sheet時若包含中文,也會報錯。
#打開文件 file = open(filename,'rb') #打開excel文件 workbook = xlrd.open_workbook(filename) #獲取sheet sheet = workbook.sheet_by_name(sheetname)
解決方案:
♦對參數進行轉碼即可。如:
filename = filename.decode('utf-8')
♦也試過unicode函數,不過,在ride中運行時出現了報錯,所以不贊成使用。
filename = unicode(filename,'utf-8')
2.為什么使用xlrd模塊?
♦在UI自動化或者接口自動化中數據維護是一個核心,所以此模塊非常實用。
3.怎樣使用xlrd模塊?
我們來舉一個從Excel中讀取賬號和密碼的例子並調用:
♦1.制作Excel我們要對以上輸入的用戶名和密碼進行參數化,使得這些數據讀取自Excel文件。我們將Excel文件命名為data.xlsx,其中有兩列數據,第一列為username,第二列為password。
♦2.讀取Excel代碼如下
#-*- coding:utf-8 -*- import xlrd,time,sys,unittest #導入xlrd等相關模塊 class Data_Excel(unittest.TestCase):# 封裝在Data_Excel類里面方便后面使用 file_addrec = r'C:\Users\liqiang22230\Desktop\date.xlsx' #定義date.xlsx數據維護Excel的路徑文件 def open_excel(self,file = file_addrec):#file = file_addrec #注意在class中def中一定要帶self try:#檢驗文件有沒有被獲取到 self.data =xlrd.open_workbook(file) return self.data except Exception : print(file) print('eero') def excel_table_byindex(self,file = file_addrec,colnameindex=0,by_index='用戶表'): #把這個讀取Excel中封裝在excel_table_byindex函數中,這時需要三個參數1.文件2.sheet名稱,列所在的行數 self.data = xlrd.open_workbook(file)#獲取Excel數據 self.table = self.data.sheet_by_name(by_index)#使用sheet_by_name獲取sheet頁名叫用戶表的sheet對象數據 self.colnames = self.table.row_values(colnameindex)#獲取行數下標為0也就是第一行Excel中第一行的所有的數據值 self.nrows = self.table.nrows #獲得所有的有效行數 list = []#總體思路是把Excel中數據以字典的形式存在字符串中一個字典當成一個列表元素 for rownum in range(1,self.nrows): row = self.table.row_values(rownum)#獲取所有行數每一行的數據值 if row: app = {}#主要以{'name': 'zhangsan', 'password': 12324.0},至於字典中有多少元素主要看有多少列 for i in range(len(self.colnames)): #在這個Excel中,列所在的行有兩個數據,所以沒循環一行就以這兩個數據為鍵,行數的值為鍵的值,保存在一個字典里 app[self.colnames[i]] = row[i] list.append(app) print(list) return list a = Data_Excel() a.excel_table_byindex() if __name__=="__main__": unittest.main()
執行結果如下:
Testing started at 15:47 ... [{'name': 'zhangsan', 'password': 12324.0}, {'name': 'zhangsan', 'password': 12324.0}, {'name': 'lisi', 'password': 923848.0}, {'name': 'lisi', 'password': 923848.0}, {'name': 'wangmazi', 'password': 213123.0}, {'name': 'wangmazi', 'password': 213123.0}] Process finished with exit code 0 Empty test suite.
♦3.調用Excel代碼如下:
def Login(self): listdata = excel_table_byindex("E:\\data.xlsx",0)#傳入兩個參數1.文件路徑2.第一行所在下標 if (len(listdata) <= 0 ):#判斷list列表中是否有數據 assert 0 , u"Excel數據異常" for i in range(0 , len(listdata) ):#循環出list中所有的字典 self.driver = webdriver.Chrome() self.driver.get("http://www.effevo.com") assert "effevo" in self.driver.title #點擊登錄按鈕 self.driver.find_element_by_xpath(".//*[@id='home']/div/div[2]/header/nav/div[3]/ul/li[2]/a").click() time.sleep(1) self.driver.find_element_by_id('passname').send_keys(listdata[i]['username'])#切出list下標下標為i的字典鍵為username的值 self.driver.find_element_by_id('password').send_keys(listdata[i]['password'])#切出list下標下標為i的字典鍵為password的值 self.driver.find_element_by_xpath(".//*[@id='content']/div/div[6]/input").click() time.sleep(2)
self.driver.close()
# 一段完整的代碼,循環登錄,取Excel中的用戶名和密碼去執行
import xlrd
import time
from selenium import webdriver
class Data_Excel(): #封裝在Data_Excel類里面方便后面使用
file_addrec = r"E:\data-excel.xlsx" #定義的數據文件
def open_excel(self,file = file_addrec):
#檢查文件有沒有被打開
try:
self.data = xlrd.open_workbook(file)
except:
print (file+"error")
def excel_table_byindex(self,file=file_addrec,colnameindex=0,by_index='用戶表'):
# 把這個讀取Excel中封裝在excel_table_byindex函數中,這時需要三個參數1.文件2.sheet名稱3,列所在的行數
self.data = xlrd.open_workbook(file) # 打開文件,獲取Excel數據
self.table = self.data.sheet_by_name(by_index) # 獲取sheet工作表,使用sheet_by_name獲取sheet頁名叫用戶表的sheet對象數據
self.colnames = self.table.row_values(colnameindex) # 獲取行數下標為0也就是第一行Excel中第一行的所有的數據值
self.nrows = self.table.nrows # 獲得所有的有效行數
list = [] # 總體思路是把Excel中數據以字典的形式存在字符串中一個字典當成一個列表元素
for rownum in range(1, self.nrows): #去除定義的首行
row = self.table.row_values(rownum) # 獲取所有行數每一行的數據值
# print(row)
# print(self.colnames)
if row:
app = {} # 主要以{'name': 'zhangsan', 'password': 12324.0},至於字典中有多少元素主要看有多少列
for i in range(len(self.colnames)):
# 在這個Excel中,列所在的行有兩個數據,所以沒循環第一行就以這兩個數據為鍵,行數的值為鍵的值,保存在一個字典里
app[self.colnames[i]] = row[i]
list.append(app)
# print(list)
return list
def Login(self):
listdata = Data_Excel().excel_table_byindex(r"E:\data-excel.xlsx", 0) # 傳入兩個參數1.文件路徑2.第一行所在下標
if (len(listdata) <= 0): # 判斷list列表中是否有數據
assert 0, u"Excel數據異常"
for i in range(0, len(listdata)): # 循環出list中所有的字典
self.driver = webdriver.Chrome()
self.driver.get("http://www.effevo.com")
assert "工作雲 - WorkYun - 團隊協作 項目-缺陷-文檔 管理工具" in self.driver.title
# 點擊登錄按鈕
self.driver.find_element_by_css_selector(".pull-left li:nth-child(1)>[class='login-in']").click()
time.sleep(1)
self.driver.find_element_by_id('passname').send_keys(listdata[i]['name']) # 切出list下標下標為i的字典鍵為username的值
self.driver.find_element_by_id('password').send_keys(str(listdata[i]['password'])) # 切出list下標下標為i的字典鍵為password的值
self.driver.find_element_by_xpath(".//*[@id='content']/div/div[6]/input").click()
time.sleep(2)
self.driver.close()
if __name__ == "__main__":
a = Data_Excel()
listdata = a.excel_table_byindex(r"E:\data-excel.xlsx", 0) # 傳入兩個參數1.文件路徑2.第一行所在下標
if (len(listdata) <= 0): # 判斷list列表中是否有數據
assert 0, u"Excel數據異常"
for i in range(0, len(listdata)): # 循環出list中所有的字典
driver = webdriver.Chrome()
driver.get("http://www.effevo.com")
assert "工作雲 - WorkYun - 團隊協作 項目-缺陷-文檔 管理工具" in driver.title
# 點擊登錄按鈕
driver.find_element_by_css_selector(".pull-left li:nth-child(1)>[class='login-in']").click()
time.sleep(1)
driver.find_element_by_id('passname').send_keys(listdata[i]['name']) # 切出list下標下標為i的字典鍵為username的值
driver.find_element_by_id('password').send_keys(
str(listdata[i]['password'])) # 切出list下標下標為i的字典鍵為password的值
driver.find_element_by_xpath(".//*[@id='content']/div/div[6]/input").click()
time.sleep(2)
driver.close()