python关于openpyxl的二次开发

from openpyxl import load_workbook
class Excel_util:
    def __init__(self,path):
        self.path=path
        # 加载输入路径的文件
        self.wb=load_workbook(self.path)
    #获取excel的sheet页
    def get_sheetname(self):
        return self.wb.sheetnames
    #输入指定sheetname
    def __call__(self, name):
        return self.wb[name]
    #读取excel内容,name是sheet页的名字,start和end是行或者列的起始
    def read_excel(self,name,start,end=None):
        """
        :param name = sheetname
        cell_range: util column(A-C) eg: start="A" end="C"
        util row (1-3) eg: start=1 end=3
        :return:
        """
        #把start和end都设为大写
        start=str(start).upper()
        if not end:
            end=start
        end = str(end).upper()
        sheet = self.__call__(name)[start:end]
        try:
            return [[cell.value for cell in _] for _ in sheet ]
        except:
            return [cell.value for cell in sheet]
    #单个单元格写入数据
    def write_cell_data(self,name,cellname,data):
        cell=self.__call__(name)[cellname]
        cell.value=data
        self.wb.save(self.path)
    #最后一行追加插入数据,需要list
    def append_row_data(self,name,data: list):
        self.__call__(name).append(data)
        self.wb.save(self.path)


# data="测试"
# data1=["ceshi"]
# a=Excel_util("D:\zhijing_work\测试数据\测试文件\yetangjian.xlsx").read_excel("Sheet1",1,3)
# print(a)
# b=Excel_util("D:\zhijing_work\测试数据\测试文件\yetangjian.xlsx")
# b.write_cell_data("Sheet1","B5",data)
# b.append_row_data("Sheet1",data1)

 

posted @ 2022-02-09 17:35  yetangjian  阅读(56)  评论(0编辑  收藏  举报