(1)安裝python官方excel庫-->xlrd
(2)獲取excel檔案位置並讀取
(3)讀取sheet
(4)讀取指定rows和cols內容
# -*- coding: utf-8 -*-解決方法:先判斷單元格內容再處理import xlrd
from datetime import date,datetime
def read_excel():
#檔案位置
excelfile=xlrd.open_workbook(r'c:\users\administrator\desktop\testdata.xlsx')
#獲取目標excel檔案sheet名
print excelfile.sheet_names()
#------------------------------------
#若有多個sheet,則需要指定讀取目標sheet例如讀取sheet2
#sheet2_name=excelfile.sheet_names()[1]
#------------------------------------
#獲取sheet內容【1.根據sheet索引2.根據sheet名稱】
#sheet=excelfile.sheet_by_index(1)
sheet=excelfile.sheet_by_name('testcase002')
#列印sheet的名稱,行數,列數
print sheet.name,sheet.nrows,sheet.ncols
#獲取整行或者整列的值
rows=sheet.row_values(2)#第三行內容
cols=sheet.col_values(1)#第二列內容
print cols,rows
#獲取單元格內容
print sheet.cell(1,0).value.encode('utf-8')
print sheet.cell_value(1,0).encode('utf-8')
print sheet.row(1)[0].value.encode('utf-8')
#列印單元格內容格式
print sheet.cell(1,0).ctype
if__name__ =='__main__':
read_excel()
問題1:假如我們修改其中乙個值為年份,讀不出正確數字,而是數字
ctype介紹 :
0empty 1string 2number 3date 4boolean 5error
-------------------------------------
需要注意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
python讀取Excel例項詳解
1.操作步驟 1 安裝python官方excel庫 xlrd 2 獲取excel檔案位置並讀取 3 讀取sheet 4 讀取指定rows和cols內容 2.示例 coding utf 8 import xlrd from datetime import date,datetime def read ...
python讀取excel檔案
一 安裝xlrd模組 二 使用介紹 1 匯入模組 import xlrd 2 開啟excel檔案讀取資料 data xlrd.open workbook excelfile.xls 3 使用技巧 獲取乙個工作表 table data.sheets 0 通過索引順序獲取 table data.shee...
python讀取excel檔案
coding utf 8 import xlrd 路徑前加 r,讀取的檔案路徑 file path r f test.xlsx 檔案路徑的中文轉碼 file path file path.decode utf 8 獲取資料 data xlrd.open workbook file path 獲取sh...