Python中读取excel文件的利器:xlrd

ew3y 9年前

xlrd是Python中常用于解析excel文件的模块,提供了非常简单易用的API来完成相关操作.

相应地,xlwt常用于向excel文件中写入内容.

xlrd的常用使用方法如下:

import xlrd

book = xlrd.open_workbook("speechs.xlsx", "utf8")

sheet = book.sheet_by_name(u'机器地址') # 通过名字来查找对应的sheet

rows = sheet.nrows # 读取行数

for row in xrange(row):

row_value = sheet.row_values(row) # 读取一行的数据

ip = str(row_value[1]) # 从数组中按序号即可获取对应的cell的值.

另外,xlrd的其他方法如下,

sheet = book.sheets()[0] # 通过sheet的索引顺序来获取

sheet = book.sheet_by_index(0)

ncols = sheet.ncols # 获取列数

sheet.col_values(col) # 获取一列数据

cell = sheet.cell(0, 0).value # 通过cell位置获取cell的值

cell = sheet.row[0][0].value # 通过行列索引来获取cell的值

通过put_cell来向cell中写入值, sheet.put_cell(row, col, ctype, value, xf),

如 sheet.put_cell(0, 0, 1, 'cell_value', 0)

ctype表示类型,0-empty, 1-string, 2-number, 3-date, 4-boolean, 5-error.

以上即为使用xlrd来解析excel文件的基本用法.