到python官网下载http://pypi.python.org/pypi/xlrd模块安装。
#coding:utf-8
1、导入模块
import xlrd
2、打开Excel文件读取数据
data = xlrd.open_workbook('C:/testmail.xlsx')
3、获取一个工作表
table = data.sheets()[0] #通过索引顺序获取
# table = data.sheet_by_index(0) #通过索引顺序获取
# table = data.sheet_by_name(u'Sheet1')#通过名称获取
#print "工作表名:",data.sheet_names()
4、 获取行数和列数:
nrows = table.nrows
ncols = table.ncols
print '行数:%s' % nrows
print "列数: %s" % ncols
for i in range(nrows ):
print "第%s行:"%i,table.row_values(i)
5、获取整行和整列的值(返回类型是list)
print "整行行值:",table.row_values(0)
print "整列列值:",table.col_values(0)
6、 获取单元格值
方法1:
cell_B2 = table.row_values(1)[1] #中文时可能需要编码 .encode('utf-8') 或encode(gb2312)
cell_C4 = table.row_values(3)[2] #中文时可能需要编码 .encode('utf-8') 或encode(gb2312)
print "方法1---行值:",cell_B2
print "方法1---列值:",cell_C4
#方法2:使用行列索引
cell_B2 = table.row(1)[1].value
cell_C4 = table.col(2)[3].value
print "方法2---行值:",cell_B2
print "方法2---列值:",cell_C4
#获取单元格值方法3:
cell_B2 = table.cell(1,1).value
cell_C4 = table.cell(1,2).value
print "方法3---行值:",cell_B2
print "方法3---列值:",cell_C4
#获取单元格值方法4:
cell_B2 = table.cell_value(rowx=1,colx=1)
cell_C4 = table.cell_value(rowx=1,colx=2)
print "方法4---行值:",cell_B2
print "方法4---列值:",cell_C4