Python 读取整个excel数据,指定行数据和指定列数据解决方法

import xlrd

class operateExcel(object):

    def __init__(self, filepath="../user_list_命名格式.xls", sheet_name="users"):
        self.filepath = filepath # excel所在路径
        self.sheet_name = sheet_name # excel中sheet页的名字
        self.data = xlrd.open_workbook(self.filepath) 
        self.table = self.data.sheet_by_name(self.sheet_name) #获取数据对象
        self.rows = self.table.nrows # 获取excel所有有效行
        self.cols = self.table.ncols # 获取excel所有有效列
        self.table_header = self.table.row_values(0) # 获取指定sheet中的表头

    # 读取表格中所有的数据
    def read_all_excel(self):
        datas = []
        for i in range(1, self.rows):
            sheet_data = {}
            for j in range(self.cols):
                #  获取单元格数据
                c_cell = self.table.cell(i, j)
                sheet_data[self.table_header[j]] = c_cell
                datas.append(sheet_data)
        return datas

    # 读取表格中指定列数据
    def read_special_col_data(self, col=0):
        datas = []
        for i in range(1, self.rows):
            c_cell = self.table.cell(i, col)
            tmp_data = c_cell
            datas.append(tmp_data)
        return datas

    # 读取表格中指定行的数据
    def read_special_row_data(self, row=0):
        for i in range(1, self.rows):
            row_data = self.table.row_values(row)
            return row_data


if __name__ == "__main__":
    print(operateExcel().read_all_excel())  # 读取整个表格的数据
    print(operateExcel().read_special_col_data(col=2))  # 读取excel第二列数据
    print(operateExcel().read_special_row_data(row=1))  # 读取excel第一行数据
  • 7
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值