今天来实战演示如何封装读取Excel方法
sheet
页命名为:login
学习技术交流群:704807680
path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
注:os.path.dirname()
获取的是上一级目录,需要几层就写几次,os.path.realpath()
是获取当前文件位置,__file__
是表示当前文件
excel = openpyxl.load_workbook(filename)
excel[self.sheetname]
目的是每次操作Excel文件都可以直接完成上面操作的初始化
import os
import openpyxl
class ReadExcel:
def __init__(self,filename,sheetname):
path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
filename = os.path.join(path,filename)
self.sheetname = sheetname
excel = openpyxl.load_workbook(filename)
self.sheet = excel[self.sheetname]
结合for
循环遍历Excel的每一行,内部再嵌套第二层for
循环读取每一行中每一个单元格的值,最后写入一个新的双层list中
def readAll(self):
res = []
for i in range (1,self.sheet.max_row+1):
lis = []
for j in range(1,self.sheet.max_column+1):
lis.append(self.sheet.cell(i,j).value)
res.append(lis)
return res[1:]
import os
import openpyxl
class ReadExcel:
def __init__(self,filename,sheetname):
path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
filename = os.path.join(path,filename)
self.sheetname = sheetname
excel = openpyxl.load_workbook(filename)
self.sheet = excel[self.sheetname]
def readAll(self):
res = []
for i in range (1,self.sheet.max_row+1):
lis = []
for j in range(1,self.sheet.max_column+1):
lis.append(self.sheet.cell(i,j).value)
res.append(lis)
return res[1:]
if __name__ == '__main__':
filename = 'conf/data.xlsx'
re = ReadExcel(filename,'login')
res = re.readAll()
print(res)