Python_excel的简单封装(Openpyxl)

封装一个excel的类

一、

from openpyxl import Workbook
from openpyxl import load_workbook

class 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 Workbook
from openpyxl import load_workbook

class 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))

 

转载于:https://www.cnblogs.com/rychh/articles/11524710.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值