一 用xlrd读取excel
首先安装xlrd的库
import xlrd
1. 打开excel
找到文件地址
找到当前文件所在的文件夹————文件夹的上一级
cur_dir = os.path.dirname(os.path.dirname(__file__))
拼接文件夹所在的路径
excel = cur_dir+"/testData/data.xls"
print(excel)
变量名= xlrd.open("文件的地址")
readbook = xlrd.open_workbook(excel)
2. 获取读入文件(excel)的sheet
a.根据页面索引的方式定位
sheet1 = readbook.sheet_by_index(0)
b.根据页面的名字定位
sheet2 = readbook.sheet_by_name("testdata")
c.返回所有sheet页的名字组成的列表
sheet3 = readbook.sheet_names()
3. 获取最大的行数和列数
a. 获取行数
max_rows = sheet1.nrows
b. 获取列数
max_col = sheet1.ncols
4. 获取某行或某列的值
a.获取第0行
# 获取行数据
row_value = sheet1.row_values(0)
b. 获取第0列
# 获取列数据
col_value = sheet1.col_values(0)
5获取某个单元格的值
a.获取第一行第一列的值
lng = sheet1.cell(0, 0)
b. 获取第2行第5列的值
lat = sheet1.cell(1, 4)
二. 接口测试:在common中创建readExcel分析和代码
import os.path
import xlrd
class ReadExcel(object):
def __init__(self):
# 1确定excel的位置
self.cur_dir = os.path.dirname(os.path.dirname(__file__))
self.excel = self.cur_dir + "/testData/data.xls"
# 2打开excel
self.readbook = xlrd.open_workbook(self.excel)
# 3确定sheet页
self.sheet = self.readbook.sheet_by_index(0)
# 4获取行数和列数
self.row_num = self.sheet.nrows
# 5定义一个列表datalist接收所有的数据
self.datalist = []
def read(self):
# 6获取第一行数据,作为所有的key
key = self.sheet.row_values(0)
# 7获取其余每行数据,作为所有的value ⭐
for i in range(1, self.row_num):
value = self.sheet.row_values(i)
# 8字典推导式,合并key和value ⭐
dict1 = {key[j]: value[j] for j in range(len(key))}
# 9将字典添加到列表中
self.datalist.append(dict1)
# 10return 数据
return self.datalist
# 调试
if __name__ == '__main__':
# 实例一个对象
res = ReadExcel()
print(res.read())