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