xlrd是python用于读取excel的第三方扩展包,在使用之前需要安装xlrd库。
pip show xlrd #检查是否已经安装
pip install -U xlrd #安装xlrd库
使用介绍:
- 导入模块
import xlrd from xlrd import open_workbook
- 打开excel表
excel=open_workbook("excel.xls")
- 获取表格
#通过索引顺序获取
table=excel.sheets()[0] table=excel.sheet_by_index(0) #通过工作表名获取
table=excel.sheet_by_name(u"Sheet1")
- 获取行数和列数
#获取行数
hs = table.nrows #获取列数
ls = table.ncols
- 获取一行、一列的值(注意:行号,列号是从索引0开始的)
#打印第一行的值,返回值为列表
rows_values = table.row_values(0) print (rows_values) #打印第一列的值,返回值为列表
cols_values = table.col_values(0) print (cols_values )
- 循环行列表值,获取所有行和列的值
#获取行数 hs=table.nrows
#通过行数值的多少遍历出表格中的值
for i in range(1,hs): print table.row_values(i)
- 应用小实例,将excel表格中的内容保存到一个列表中,并输出列表内容
#coding=utf-8
import xlrd excel=xlrd.open_workbook(u"test.xlsx") table=excel.sheet_by_index(0) hs=table.nrows data = [] for i in range(0,hs): #print table.row_values
data.append(table.row_values) print (data)