今天把前面的代码重构了下,用类的方式来实现下:
import openpyxl
class ExcelSheet(object):
"""comment"""
def __init__(self,excel_path, sheet_index=-1):
self.wb = openpyxl.load_workbook(excel_path)
if sheet_index == -1:
self.ws = self.wb.active
else:
self.ws = self.wb.worksheets[sheet_index]
self.title = self.ws.title
def get_real_max_column(self):
real_max_column = self.ws.max_column
columns = [column for column in self.ws.columns]
while real_max_column>0:
column_dict = {c.value for c in columns[real_max_column-1]}
if column_dict=={None}:
real_max_column = real_max_column-1
else:
break
return real_max_column
def get_real_max_row(self):
i=self.ws.max_row
real_max_row = 0
while i > 0:
row_dict = {i.value for i in self.ws[i]}
if row_dict == {None}:
i = i-1
else:
real_max_row = i
break
return real_max_row
if __name__ == '__main__':
path = r'e:\投标记录.xlsx'
sheet = ExcelSheet(path)
real_max_column = sheet.get_real_max_column()
real_max_row = sheet.get_real_max_row()
print(real_max_column,real_max_row)
print(sheet.title)
为了方便以后的使用,封装了一个sheet的类,准备以后把类似sheet的属性的东西放到这个类里。