上一期給你們分享瞭如何用Python讀取文本,此次給你們分享如何讀取Excel表格內容,拿最多見的.xlsx和.xls格式來說解。app
本章主要知識點有:函數
正文:spa
讀取Excel有多種方法,本章採用比較通用的xlrd庫來實現,先讀取文件,再指定到某sheet頁進行讀取excel
data = xlrd.open_workbook(filename)
table = data.sheet_by_name(sheetName)
如上代碼中,將sheet頁賦給了table變量,再根據table頁的總行數和總列數,逐個輸出單元格的內容code
# 獲取總行數和總列數 tRows = table.nrows tCols = table.ncols #獲取某個單元格的內容 table.cell(r,c).value
結合以上信息,能夠完整的輸出讀取sheet頁內容的函數,並輸出list格式blog
1 def readBySheet(self, sheetName : str) -> list: 2 data = xlrd.open_workbook(self.files) 3 4 # get table cont by sheet name 5 table = data.sheet_by_name(sheetName) 6 7 tRows = table.nrows 8 tCols = table.ncols 9 10 # read Excel 11 res = [] 12 for r in range(tRows): 13 rescol = [] 14 for c in range(tCols): 15 rescol.append(table.cell(r,c).value) 16 res.append(rescol) 17 return res
既然均可以輸出某sheet頁的內容了,那麼讀取整篇excel 的內容,只要知道全部sheet頁的名稱便可,xlrd庫也提供了這樣一種方法 data.sheet_names(),即輸出seheet頁的列表,結合以上代碼,那麼讀取整篇excel的方法實現以下開發
1 def read(self) -> list: 2 data = xlrd.open_workbook(self.files) 3 tablelist = data.sheet_names() 4 5 res = [] 6 for name in tablelist: 7 res.append(self.readBySheet(name)) 8 return res
擴展:get
在開發項目中,有時並不須要讀取整個table頁的內容,或許只須要某一列或某一行的值,其實xlrd早就考慮到了,使用 table.row_values(row)和table.col_values(col),其中row 和 col 爲行和列index,小編也將其封裝好了,方便讀者直接調用pandas
1 def readAnyRows(self, sheetName : str, row : int) -> list: 2 data = xlrd.open_workbook(self.files) 3 table = data.sheet_by_name(sheetName) 4 return table.row_values(row) if table.nrows > row else 'row out of range' 5 6 def readAnyCols(self, sheetName : str, col : int) -> list: 7 data = xlrd.open_workbook(self.files) 8 table = data.sheet_by_name(sheetName) 9 return table.col_values(col) if table.ncols > col else 'col out of range'
瞭解了以上幾種方法,我相信在處理表格場景時均可以遊刃有餘。建議封裝成模塊,方便循環使用。若是想要現成的模塊,評論+關注私信我,留下郵箱並回復關鍵詞「excel」,我會第一時間發給你的哦。table
後續我會介紹其餘讀取excel的方式,譬如openpyxl,pandas等,關注我,你會對Python愈來愈有興趣!