
xlrd模块
python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。
安装xlrd模块
使用pip命令:
pip install xlrd
验证是否安装成功
进入python:
$ python
导入xlrd
模块:

如图,表示安装成功.
打开execl文件
x1 = xlrd.open_workbook("data.xlsx")
操作sheet
函数 | 含义 |
---|---|
table = x1.sheets()[0] |
通过索引顺序获取 |
table = x1.sheet_by_index(sheet_indx)) |
通过索引顺序获取 |
table = x1.sheet_by_name(sheet_name) |
通过名称获取 |
以上三个函数都会返回一个xlrd.sheet.Sheet()对象
操作行
函数 | 含义 |
---|---|
nrows = table.nrows |
获取该sheet中的有效行数 |
table.row(rowx) |
返回由该行中所有的单元格对象组成的列表 |
table.row_slice(rowx) |
返回由该列中所有的单元格对象组成的列表 |
table.row_types(rowx, start_colx=0, end_colx=None) |
返回由该行中所有单元格的数据类型组成的列表 |
table.row_values(rowx, start_colx=0, end_colx=None) |
返回由该行中所有单元格的数据组成的列表 |
table.row_len(rowx) |
返回该列的有效单元格长度 |
操作列
函数 | 含义 |
---|---|
ncols = table.ncols |
获取列表的有效列数 |
table.col(colx, start_rowx=0, end_rowx=None) |
返回由该列中所有的单元格对象组成的列表 |
table.col_slice(colx, start_rowx=0, end_rowx=None) |
返回由该列中所有的单元格对象组成的列表 |
table.col_types(colx, start_rowx=0, end_rowx=None) |
返回由该列中所有单元格的数据类型组成的列表 |
table.col_values(colx, start_rowx=0, end_rowx=None) |
返回由该列中所有单元格的数据组成的列表 |
操作单元格
函数 | 含义 |
---|---|
table.cell(rowx,colx) |
返回单元格对象 |
table.cell_type(rowx,colx) |
返回单元格中的数据类型 |
table.cell_value(rowx,colx) |
返回单元格中的数据 |
table.cell_xf_index(rowx, colx) |
暂时还没有搞懂 |
测试
表格内容:

代码:
#!/usr/bin/python
# # -*- coding: utf-8 -*-
import xlrd
if __name__ == '__main__':
work_book = xlrd.open_workbook("./pytest.xlsx")
table = work_book.sheets()[0]
print table.cell_value(0,0),' ',table.cell_value(0,1)
for index in range(2, table.nrows):
print table.cell_value(index,0),' ',table.cell_value(index,1)
执行结果

网友评论