python读取excel某⼀列内容-Python读取Excel数据并根据列名
取值
⼀直想将⾃⼰接触到的东西梳理⼀遍,可就是迈不出第⼀步,希望从这篇总结开始不要再做⾏动的矮⼈了。
最近测试过程中需要⽤到python读取excel⽤例数据,于是去了解和学习了下xlrd库,这⾥只记录使⽤过程中读取excel数据相关操作。
⼀、安装xlrd库
可以下载xlrd库包到本地安装,也可以通过pip命令安装,这⾥我选择pip命令:
pip install xlrd
⼆、使⽤xlrd读取excel数据
具体详细的操作可以参考xlrd库操作说明⽂档,以下是两种读取excel数据的⽅法:
1、根据Excel中sheet名称读取数据:
1 defreadExcelDataByName(fileName, sheetName):
2 table =None
3 errorMsg =None
4 try:
5 data
=xlrd.open_workbook(fileName)6 table =data.sheet_by_name(sheetName)7 exceptException, msg:8 errorMsg =msg9 return table, errorMsg
python怎么读取excel某一列2、根据Excel中sheet的序号获取:
1 defreadExcelDataByIndex(fileName, sheetIndex):
2 table =None
3 errorMsg = ""
4 try:
5 data =xlrd.open_workbook(fileName)
6 table =data.sheet_by_index(sheetIndex)
7 exceptException, msg:
8 errorMsg
=msg9 return table, errorMsg
3、根据列名获取相应序号,由于有时读取excel中列数据时,需要通过列头名称获取相应的列中的值,所以写了下⾯这个返回列名所在表格中的index。然后就可以直接通过ll_value(i, getColumnIndex(table,'列名'))获取列的值。
1 defgetColumnIndex(table, columnName):
2 columnIndex =None3
3 for i ls):5
4 ll_value(0, i) ==columnName):
5 columnIndex =i
6 break
7 return columnIndex
下⾯加⼊需要读取如下excel表格中的数据,在读取数据时直接根据列名去获取相应的值。
根据列名读取相应的值,代码如下:
1 #!/usr/bin/python
2 #coding=utf-8
3 __author__ = 'Paul'
4 importxlrd
5 importchardet
6 importtraceback
7 defgetColumnIndex(table, columnName):
8 columnIndex =None
9 #print table
10 for i ls):11 #print columnName
12 #ll_value(0, i)
13 ll_value(0, i) ==columnName):14 columnIndex =i15 break
16 returncolumnIndex17 defreadExcelDataByName(fileName, sheetName):18 #print fileName
19 table =None20 errorMsg = ""
21 try:22 data =xlrd.open_workbook(fileName)23 table =data.sheet_by_name(sheetName)24 exceptException, msg:25 errorMsg =msg26 returntable, errorMsg27 defreadExcelDataByIndex(fileName, sheetIndex):28 table =None29 errorMsg = ""
30 try:31 data =xlrd.open_workbook(fileName)32 table =data.sheet_by_index(sheetIndex)33 exceptException, msg:34 errorMsg =msg35 returntable, errorMsg36 if __name__ == '__main__':37 #example
38 xlsfile= 'F:/test_AutoTesting/TestCase/RunList.xlsx'
39 table = readExcelDataByName(xlsfile, 'Sheet1')[0]40 #获取第⼀⾏的值
41 testcase_id = ll_value(1, getColumnIndex(table,'TestCaseID'))42 app_config = ll_value(1,
getColumnIndex(table,'APPConfig'))43
44 print u'测试⽤例ID为:%s'%(testcase_id)45 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) #转成str

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。