封装一个excel的类
一、
from openpyxl import Workbookfrom openpyxl import load_workbookclass ExcelUtil(object): def __init__(self,excel_file_path,current_sheet_name=None): self.excel_file_path = excel_file_path try: self.wb = load_workbook(self.excel_file_path) except: print("加载excel文件 %s 失败" %self.excel_file_path) try: if current_sheet_name is None: self.ws = self.wb.active else: self.ws = self.wb[current_sheet_name] except: print("指定的sheet %s 不存在!" %current_sheet_name) def set_current_sheet(self,sheet_name): self.ws = self.wb[sheet_name] def get_current_sheet(self): return self.ws.title def get_cell_value(self,row_no,col_no): return self.ws.cell(row=row_no,column=col_no).value if __name__=="__main__": excel_file=ExcelUtil("e:\\sample.xlsx") print(excel_file.excel_file_path) excel_file.set_current_sheet("Sheet1") print(excel_file.get_current_sheet()) excel_file.set_current_sheet("Sheet") print(excel_file.get_cell_value(2,2)
二、
from openpyxl import Workbookfrom openpyxl import load_workbookclass ExcelUtil(object): def __init__(self,excel_file_path,current_sheet_name=None): self.excel_file_path = excel_file_path try: self.wb = load_workbook(self.excel_file_path) except: print("加载excel文件 %s 失败" %self.excel_file_path) try: if current_sheet_name is None: self.ws = self.wb.active else: self.ws = self.wb[current_sheet_name] except: print("指定的sheet %s 不存在!" %current_sheet_name) def set_current_sheet(self,sheet_name): self.ws = self.wb[sheet_name] def get_current_sheet(self): return self.ws.title def get_cell_value(self,row_no,col_no): return self.ws.cell(row=row_no,column=col_no).value if __name__=="__main__": excel_file=ExcelUtil("e:\\sample.xlsx") print(excel_file.excel_file_path) excel_file.set_current_sheet("Sheet1") print(excel_file.get_current_sheet()) excel_file.set_current_sheet("Sheet") print(excel_file.get_cell_value(2,2))