安装xlrd
模块
pip install xlrd==1.2.0
xlrd包使用起来本就十分友好,可以不必单独封装,这里只是为了展示和方便理解
# _*_ coding: utf-8 _*_
import xlrd # pip install xlrd==1.2.0 1.2.0版本支持.xlsx
class Excel:
def __init__(self, file_path: str, sheet: int = 0) -> None:
excel = xlrd.open_workbook(file_path) # 打开文件
self.table = excel.sheets()[sheet] # 得到sheet页
self.nrows = self.table.nrows # 总行数
self.ncols = self.table.ncols # 总列数
def get_row(self, inx: int) -> dict:
if isinstance(inx, int):
# 返回可以用英文索引的字典
return {chr(a): self.table.cell(inx, i).value for i, a in enumerate(range(ord('A'), ord('Z') + 1))}
def get_col(self, inx: int or str) -> list:
if isinstance(inx, int):
return self.table.col_values(inx) # 获取列 ↓
elif isinstance(inx, str):
return self.table.col_values(ord(inx) - ord('A'))
if __name__ == '__main__':
xls = Excel('./Record.xls')
print(xls.get_col(1))