python学习6--python读取excel数据
python怎么读取excel文件数据⼀、xlrd模块介绍
1.xlrd是读取excel表格数据;
2.⽀持xlsx和xls格式的excel表格
3.安装⽅式:pip install xlrd
4.模块导⼊⽅式:import xlrd
⼆、环境准备
1.先安装xlrd模块,打开cmd,输⼊pip install xlrd在线安装
三、基本操作
import xlrd
#打开excle表格,参数是⽂件路径
a=xlrd.open_workbook("E:\\sys_user.xls")
#table=a.sheets()[0] #通过索引顺序获取
# table=a.sheet_by_index(0) #通过索引顺序获取
table=a.sheet_by_name("user") #通过名称获取
ws #获取总⾏数
ls #获取总列数
print(nrows,ncols)
#获取⼀⾏或⼀列的值,参数是第⼏⾏
w_values(0)) #获取第⼀⾏值
l_values(0)) #获取第⼀列值
 运⾏结果:
20 2
['test1', 1.0]
['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'test9', 'test10', 'test11', 'test12', 'test13', 'test14', 'test15', 'test16', 'test17', 'test18', 'test19', 'test20']
三、excel存放数据
1.在excel中存放数据,第⼀⾏为标题,也就是对应字典⾥⾯的key值,如:username,passwd
2.如果excel数据中有纯数字的⼀定要右键》设置单元格格式》⽂本格式,要不然读取的数据是浮点数(先设置单元格格式后编辑,编辑成功左上⾓有⼩三⾓图标)
注意,我尝试先填写数字,再设置⽂本,未显⽰⼩三⾓图标;将数字内容删除,重写填写数字,显⽰⼩三⾓图标。 
四、封装读取⽅法
1.最终读取的数据是多个字典的list类型数据,第⼀⾏数据是字典⾥的key值,从第⼆⾏开始⼀⼀对应value值
2.封装好后代码如下:
import xlrd
a=xlrd.open_workbook("D:\\user.xlsx")
table=a.sheet_by_name("user")
ws
ls
print(nrows,ncols)#6,2
w_values(0)
result=[]
n=1
while n!=nrows:
d={}
w_values(n)
# print(v)
for i in range(ncols):#0,1
d[key[i]]=v[i]
result.append(d)
n+=1
# print(d)
print(result)
 运⾏结果:
6 2
[{'username': 'test1', 'passwd': '3'}, {'username': 'test2', 'passwd': '4'}, {'username': 'test3', 'passwd': '5'}, {'username': 'test4', 'passwd': '6'}, {'username': 'test5', 'passwd': '7'}] 整理成⽅法,代码如下:
import xlrd
def read_excel(filepath,sheetname):
a=xlrd.open_workbook(filepath)
table=a.sheet_by_name(sheetname)
result=[]
n=1
ws
ls
w_values(0)
while n!=nrow:
d={}
w_values(n)
for i in range(ncol):
d[key[i]]=v[i]
result.append(d)
n += 1
return result
print(read_excel("D:/user.xlsx","user"))
 运⾏结果:
[{'username': 'test1', 'passwd': '3'}, {'username': 'test2', 'passwd': '4'}, {'username': 'test3', 'passwd': '5'}, {'username': 'test4', 'passwd': '6'}, {'username': 'test5', 'passwd': '7'}] 

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