xlrd如何根據列名提取資料?
、安裝xlrd庫
可以下載xlrd庫包到本地安裝,也可以透過pip命令安裝,這裡我選擇pip命令:
pip install xlrd
二、使用xlrd讀取excel資料
具體詳細的操作可以參考xlrd庫操作說明文件,以下是兩種讀取excel資料的方法:
1、根據Excel中sheet名稱讀取資料:
def readExcelDataByName(fileName, sheetName):
table = None
errorMsg = None
try:
data = xlrd。open_workbook(fileName)
table = data。sheet_by_name(sheetName)
except Exception, msg:
errorMsg = msg 9 return table, errorMsg
2、根據Excel中sheet的序號獲取:
def readExcelDataByIndex(fileName, sheetIndex):
table = None
errorMsg = “”
try:
data = xlrd。open_workbook(fileName)
table = data。sheet_by_index(sheetIndex)
except Exception, msg:
errorMsg = msg
return table, errorMsg
3、根據列名獲取相應序號,由於有時讀取excel中列資料時,需要透過列頭名稱獲取相應的列中的值,所以寫了下面這個返回列名所在表格中的index。然後就可以直接透過table。cell_value(i, getColumnIndex(table,‘列名’))獲取列的值。
def getColumnIndex(table, columnName):
columnIndex = None 3
for i in range(table。ncols): 5
if(table。cell_value(0, i) == columnName):
columnIndex = i
break
return columnIndex
下面加入需要讀取如下excel表格中的資料,在讀取資料時直接根據列名去獲取相應的值。
根據列名讀取相應的值,程式碼如下:
#!/usr/bin/python
# coding=utf-8
__author__ = ‘Paul’
import xlrd
import chardet
import traceback
def getColumnIndex(table, columnName):
columnIndex = None
#print table
for i in range(table。ncols):
#print columnName
#print table。cell_value(0, i)
if(table。cell_value(0, i) == columnName):
columnIndex = i
break
return columnIndex
def readExcelDataByName(fileName, sheetName):
#print fileName
table = None
errorMsg = “”
try:
data = xlrd。open_workbook(fileName)
table = data。sheet_by_name(sheetName)
except Exception, msg:
errorMsg = msg
return table, errorMsg
def readExcelDataByIndex(fileName, sheetIndex):
table = None
errorMsg = “”
try:
data = xlrd。open_workbook(fileName)
table = data。sheet_by_index(sheetIndex)
except Exception, msg:
errorMsg = msg
return table, errorMsg
if __name__ == ‘__main__’:
#example
xlsfile= ‘F:/test_AutoTesting/TestCase/RunList。xlsx’
table = readExcelDataByName(xlsfile, ‘Sheet1’)[0]
#獲取第一行的值
testcase_id = table。cell_value(1, getColumnIndex(table,‘TestCaseID’))
app_config = table。cell_value(1, getColumnIndex(table,‘APPConfig’))
print u‘測試用例ID為:%s’%(testcase_id)
print u‘配置資訊為:%s’%(app_config)
得出結果如下:
4、讀取excel中的文字或數值轉換成了float的問題
有時Excel中的值為20,但讀取出來的值卻變成了20。0,這與我們想要的不大一致,特別是做UI自動化測試過程中需要下拉選擇值時就完全選不出想要的選項了。目前我想到的是透過下面的語句來處理:
if isinstance(inputValue,float): #判斷讀取到的值是否為float
if inputValue==int(inputValue): #判斷讀取到的值與轉成int後的值是否相等,如果相等則轉成int
inputValue = int(inputValue)
inputValue = str(inputValue) #轉成s