1 # -*- coding: utf-8 -*- 2 import xlrd 3 def read_excel(): 4 # 打开文件 5 workbook = xlrd.open_workbook(r'E:\pycharm project\movies.xls') 6 # 获取所有sheet 7 print workbook.sheet_names() # [u'sheet1', u'sheet2'] 8 #获取sheet2 9 sheet2_name= workbook.sheet_names()[1] 10 print sheet2_name 11 # 根据sheet索引或者名称获取sheet内容 12 sheet2 = workbook.sheet_by_name('Sheet2') 13 # sheet的名称,行数,列数 14 print sheet2.name,sheet2.nrows,sheet2.ncols 15 rows = sheet2.row_values(3) # 获取第四行内容 16 cols = sheet2.col_values(2) # 获取第三列内容 17 print rows 18 print cols 19 #获取单元格内容的三种方法 20 print sheet2.cell(1,0).value.encode('utf-8') 21 print sheet2.cell_value(1,0).encode('utf-8') 22 print sheet2.row(1)[0].value.encode('utf-8') 23 # 获取单元格内容的数据类型 24 print sheet2.cell(1,3).ctype 25 if __name__ == '__main__': 26 read_excel()
需要注意
1.python读取excel中单元格的内容返回的有5种类型,即上面例子中的ctype:
ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
2.大小写要一致
3.日期显示
if (sheet2.cell(rows,cols).ctype == 3): date_value = xlrd.xldate_as_tuple(sheet2.cell_value(4,0),workbook.datemode) date_tmp = date(*date_value[:3]).strftime('%Y/%m/%d') print date_tmp
推荐链接:http://www.cnblogs.com/zhoujie/p/python18.html