导入模块
1 | import xlrd |
打开文件
1 | x1 = xlrd.open_workbook("data.xlsx") |
获取sheet
- 获取所有sheet名字:x1.sheet_names()
- 获取sheet数量:x1.nsheets
- 获取所有sheet对象:x1.sheets()
- 通过sheet名查找:x1.sheet_by_name(“test”)
- 通过索引查找:x1.sheet_by_index(3)
1 | # -*- coding:utf-8 -*- |
输出结果:
1 | sheet_names: ['test1', 'test2', 'test3'] |
获取sheet的汇总数据:
- 获取sheet名:sheet1.name
- 获取总行数:sheet1.nrows
- 获取总列数:sheet1.ncols
1 | sheet1 = x1.sheet_by_name("test1") |
输出:
1 | sheet name: test1 |
单元格批量读取:
1
2
3
4
5
6
7 数据类型:
空:0
字符串:1
数字:2
日期:3
布尔:4
error:5
a)行操作:
- sheet1.row_values(0) # 获取第一行所有内容,合并单元格,首行显示值,其它为空。
- sheet1.row(0) # 获取单元格值类型和内容
- sheet1.row_types(0) # 获取单元格数据类型
1 | print(sheet1.row_values(0)) |
输出:
1 | ['商品名称', '商品价格', '销量'] |
b) 表操作
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) # 获取单元格值类型和内容
1
2
3sheet1.row_slice(2, 0, 2)
获取第三行,第0和第1列的值类型和内容
[text:'衬衫', number:66.0]sheet1.row_types(1, 0, 2) # 获取单元格数据类型
1
2
3sheet1.row_types(1, 0, 2)
获取第二行,第0和第1列的值类型
array('B', [1, 2]) # [1,2] 分别代表上面的字符串和数字
特定单元格读取:
a) 获取单元格值:
- sheet1.cell_value(1, 2) # 获取第二行,第三列的数据
- sheet1.cell(1, 2).value # 获取第二行,第三列的数据
- sheet1.row(1)[2].value # 获取第二行,第三列的数据
b) 获取单元格类型:
- sheet1.cell(1, 2).ctype # 获取第二行,第三列的数据类型
- sheet1.cell_type(1, 2) # 获取第二行,第三列的数据类型
- sheet1.row(1)[2].ctype # 获取第二行,第三列的数据类型
(0,0)转换A1:
xlrd.cellname(0, 0) # (0,0)转换成A1
xlrd.cellnameabs(0, 0) # (0,0)转换成$A$1
xlrd.colname(30) # 把列由数字转换为字母表示
1
2
3
4
5
6
7print(xlrd.cellname(0, 0))
print(xlrd.cellnameabs(0, 0))
print(xlrd.colname(30))
输出:
A1
$A$1
AE
读取demo
1 | # xls_file是文件对象 |
导出demo
1 | headers = [ |