安装:pip install xlrd
官网地址:
介绍:
为开发人员提供一个库,用于从Microsoft Excel(tm)电子表格文件中提取数据。
快速使用xlrdimport xlrd
book = xlrd.open_workbook("myfile.xls")
print("当前excel文件工作表数量为 {0}".format(book.nsheets))
print("工作表名字为: {0}".format(book.sheet_names()))
# 获取第一张工作表
sh = book.sheet_by_index(0)
# 获取表的数量
print(book.nsheets)
# 当前工作表名, 总行数 总列数
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
# 单元 d30 数据为
print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3)))
# 获取所有行数据
for rx in range(sh.nrows):
# rx 行
print(sh.row(rx))
>>> [text:'Camille Richardson', text:'2316 EVIAN CT', empty:'', empty:'', text:'DISTRICT HEIGHTS', text:'MD', text:'20747-1153', text:'US']
# 获取所有行数据
for rx in range(sh.nrows):
print(sh.row_values(rx))
>>> ['Camille Richardson', '2316 EVIAN CT', '', '', 'DISTRICT HEIGHTS', 'MD', '20747-1153', 'US']
常用方法:
获取工作表名称、行数、列数工作表名字:table.name
表行数:table.nrows
表列数:table.ncols
获取sheet获取所有sheet名字:book.sheet_names()
获取sheet数量:book.nsheets
获取所有sheet对象:book.sheets()
通过sheet名查找:book.sheet_by_name("demo”)
通过索引查找:book.sheet_by_index(0)
获取sheet的汇总数据:获取sheet名:sheet1.name
获取总行数:sheet1.nrows
获取总列数:sheet1.ncols
单元格批量读取:行操作:sheet1.row_values(0) # 获取第一行所有内容,合并单元格,首行显示值,其它为空。
sheet1.row(0) # 获取单元格值类型和内容
sheet1.row_types(0) # 获取单元格数据类型
列操作sheet1.row_values(0, 6, 10) # 取第1行,第6~10列(不含第10表)
sheet1.col_values(0, 0, 5) # 取第1列,第0~5行(不含第5行)
sheet1.row_slice(2, 0, 2) # 获取单元格值类型和内容
sheet1.row_types(1, 0, 2) # 获取单元格数据类型
特定单元格读取:获取单元格值:sheet1.cell_value(1, 2)
sheet1.cell(1, 2).value
sheet1.row(1)[2].value
获取单元格类型:sheet1.cell(1, 2).ctype
sheet1.cell_type(1, 2)
sheet1.row(1)[2].ctype
xlrd 常用函数# 打开excel表,是否带格式
book = xlrd.open_workbook("地址信息.xlsx",formatting_info=True/False)
# 获取excel中所有的sheet
book.sheets()
# 打开具体sheet工作方法1
sheet = book.sheet_by_index(索引位置)
# 打开具体sheet工作方法2
sheet = book.sheet_by_nam(工作表名字)
# 获取单元格的值1
sheet.cell_value(rowx=行, colx=列)
# 获取单元格的值2
sheet.cell(行,列).value
# 获取单元格的值3
sheet.cell(行)[列].value
# 获取第4行的内容,以列表形式表示
row_4 = table.row_values(3)
# 获取所有工作表的名字
book.sheet_names()
# 获取工作表的数量
book.nsheets
# 获取工作表的所有行数
sheet.nrows
# 获取工作表的所有列数
sheet.ncols