python 读取excel表数据_python读取excel合并方法

04a5b127a9e70db82b0af6229d698a89.png

合并单元数据实际应用

在实际excel中,存在合并单元来方便读写数据的情况,无论纵横都一样。然而在使用excel记录数据的需要通过某些程序读取出来进行处理的时候合并单元的数据应该处理?下面就以Python为例子,简单讲解python读取excel合并数据的方法例子。

python读取excel合并方法

# -*- coding:utf-8 -*-
import xlrd
path = "./"

class Price:
    def __init__(self, sheet):
        # 注意在读取时要添加formatting_info=True参数,默认是False,表示原样读取
        file = 'test.xlsx'
        wb = xlrd.open_workbook(path + file)
        self.table = wb.sheet_by_name(sheet)
        self.sheet = sheet

    # 合并信息
    def colspan(self):
        # 计算出合并的单元格有哪些
        colspan = {}
        if self.table.merged_cells:
            for item in self.table.merged_cells:
                # 通过循环进行组合,从而得出所有的合并单元格的坐标
                for row in range(item[0], item[1]):
                    for col in range(item[2], item[3]):
                        # 合并单元格的首格是有值的,所以在这里进行了去重
                        if (row, col) != (item[0], item[2]):
                            colspan.update({(row, col): (item[0], item[2])})
        return colspan

读取数据方法

# 读取信息结果
    def res_list(self):
        colspan = self.colspan()
        res = []
        # 开始循环读取excel中的每一行的数据
        for i in range(self.table.nrows):
            rd = []
            for j in range(self.table.ncols):
                # 假如碰见合并的单元格坐标,取合并的首格的值即可
                if colspan.get((i, j)) and colspan.get((i, j)) != (0, 0):
                    rd.append(self.table.cell_value(*colspan.get((i, j))))
                else:
                    ctype = self.table.cell(i, j).ctype  # 表格的数据类型
                    cell = self.table.cell_value(i, j)
                    if ctype == 2 and cell % 1 == 0.0:  # ctype为2且为浮点
                        cell = int(cell)  # 浮点转成整型
                    rd.append(cell)
            res.append(rd)
        return res

纵横向数据处理

由于数据呈现时候会有纵横不同的处理及查阅情况,所以需要根据实际需求编写对应方法。

横向例子

22f5fdce07b78fbc1b8f571416bf9262.png

纵向例子

# 信息下标
    def r_i(self, rc, mes, P_type="across"):
        r_i = None
        if P_type == "across":
            for i, i_v in enumerate(rc):
                if i_v == mes:
                    r_i = i
                    break
        if P_type == "vertical":
            for i, i_v in enumerate(rc):
                if i_v[0] + i_v[1] == mes:
                    r_i = i
                    break
        return r_i


    # IP价格(横向获取)
    def getIPPriceAcross(self, node):
        res = self.res_list()
        rc = []
        for ic in range(len(res[0])):
            rc.append(res[0][ic] + res[1][ic])
        for i in range(2):
            res.pop(0)
        r_i = self.r_i(rc, node)
        ip_mes = dict()
        ip_mes["节点"] = rc[r_i]
        ip_mes["价格"] = res[0][r_i]
        return ip_mes

    # IP价格(纵向获取)
    def getIPPriceVertical(self, node):
        res = self.res_list()
        rc = res[0]
        for i in range(1):
            res.pop(0)
        r_i = self.r_i(res, node, P_type="vertical")
        ip_mes = dict()
        if r_i != None:
            ip_mes["节点"] = node
            for d_i, d in enumerate(rc):
                if d == "价格":
                    ip_mes["价格"] = res[r_i][d_i]
                    break
        return ip_mes

执行方法,设定节点信息。输入excel对应的sheet名称

if __name__ == '__main__':
    node = "广东B"
    P = Price("IP_弹性 (横)")
    print("IP_弹性 (横)", P.getIPPriceAcross(node))
    P = Price("IP_弹性(纵)")
    print("IP_弹性(纵)", P.getIPPriceVertical(node))

返还结果:

IP弹性 (横) {‘节点’: ‘广东B’, ‘价格’: 2.67}

IP弹性(纵) {‘节点’: ‘广东B’, ‘价格’: 2.67}

总结

Python操作读取excel合并数据信息,这一方法可以方便日后的数据处理工作及excel的灵活编辑。无需顾虑合并后的信息无法与实际操作核验内容无法对比的情况。

睿江云官网链接:www.eflycloud.com

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值