每日10行代码146:用类的方式封装下excel的sheet,获取实际的最大行数及最大列数

176 篇文章 4 订阅
15 篇文章 2 订阅

今天把前面的代码重构了下,用类的方式来实现下:

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的属性的东西放到这个类里。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值