1.准备:
使用之前需要先按照:打开cmd,输入pip install xlrd(xlswriter),点击enter;
2.基本使用:
xlrd:
#打开els文件,参数是文件路径:
table = xlrd.open_workbook(r"F:/selenium/test.xls")
sheet = table.sheets()[2] #通过索引顺序获取
sheet = table.sheet_by_index(0) #通过索引获取
sheet = table.sheet_by_name("Sheet1") #通过名称获取
#获取总行数:
nrows = sheet.nrows
#获取总列数:
ncols = sheet.ncols
#获取特定一行或一列的值,参数是第几行:
sheet.row_values(0) #获取第一行的值
sheet.col_values(0)#获取第一列的值
获取某一单元格里面的值:
#获取单元格:
cell_A1 = sheet.cell(0,0) .value
cell_C4 = sheet.cell(2,3).value
#使用行列索引:
cell_A1 = sheet.row(0)[0].value
cell_C4 = sheet.row(3)[2].value
cell_A2 = sheet.col(0)[1].value
#coding:utf-8
import xlrd class ExcelUnit():
def __init__(self,excelPath, sheetName):
self.data = xlrd.open_workbook(excelPath)
self.table = self.data.sheet_by_name(sheetName)
#获取第一行作为key值
self.keys = self.table.row_values(0)
#获取总行数
self.rowNum = self.table.nrows
#获取总列数
self.colNum = self.table.ncols def dict_data(self):
if self.rowNum <= 1:
print("总行数小于1")
else:
r = []
j = 1
for i in range(self.rowNum - 1):
s = {}
#从第二行取对象的values值
values = self.table.row_values(j)
for x in range(self.colNum):
s[self.keys[x]] = values[x]
r.append(s)
j += 1
return r if __name__ == "__main__":
filepath = r"F:\Workspace\selenium\2_58xlrd\userdata.xls"
sheetName = "Sheet1"
data = ExcelUnit(filepath, sheetName) print data.dict_data()
参考文档;
https://www.cnblogs.com/ysjt/p/6527056.html
http://www.cnblogs.com/yoyoketang/p/6701950.html