Python 读取Excel之xlrd篇

上一期给大家分享了如何用Python读取文本,这次给大家分享如何读取Excel表格内容,拿最常见的.xlsx和.xls格式来讲解。

本章主要知识点有:

  1. 读取整篇excel返回list[list[list]] 格式
  2. 读取指定sheet页内容返回list[list[]] 格式
  3. 读取任意一行或一列返回list[] 格式

正文:

读取Excel有多种方法,本章采用比较通用的xlrd库来实现,先读取文件,再指定到某sheet页进行读取

data = xlrd.open_workbook(filename)
table = data.sheet_by_name(sheetName)

如上代码中,将sheet页赋给了table变量,再根据table页的总行数和总列数,逐个输出单元格的内容

# 获取总行数和总列数
tRows = table.nrows
tCols = table.ncols

#获取某个单元格的内容
table.cell(r,c).value

结合以上信息,可以完整的输出读取sheet页内容的函数,并输出list格式

 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

扩展:

在开发项目中,有时并不需要读取整个table页的内容,或许只需要某一列或某一行的值,其实xlrd早就考虑到了,使用 table.row_values(row)和table.col_values(col),其中row 和 col 为行和列index,小编也将其封装好了,方便读者直接调用

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”,我会第一时间发给你的哦。

后续我会介绍其他读取excel的方式,譬如openpyxl,pandas等,关注我,你会对Python越来越有兴趣!

原文地址:https://www.cnblogs.com/potato-find/p/13285761.html