zoukankan      html  css  js  c++  java
  • python如何获取多个excel单元格的值

    一. 获取多个单元格的值报错:AttributeError: 'tuple' object has no attribute 'value'

    需要读取的sample.xlsx
    在这里插入图片描述
    代码读取的是A3:B10之间的单元格

    from openpyxl import load_workbook
    
    wb = load_workbook(r"D:python_workshoppython6studysample.xlsx")
    sh = wb["Sheet"]
    
    print(sh["A3":"B10"].value)
    

    运行结果:

    Traceback (most recent call last):
      File "D:/python_workshop/python6/study/demo.py", line 8, in <module>
        print(sh["A3":"B10"].value)
    AttributeError: 'tuple' object has no attribute 'value'
    

    二. 如何解决

    上面报错信息是,元组对象没有属性"value",我们先来看一下print(sh["A2":"B10"]),得到的是一个元组,比较有意思的是,元组中的每一项也是一个元组,这个元组里存储的是每一行的单元格对象:相当于 元组(A3: B10) ——> 第三行:元组(A3: B3),第四行:元组(A4: B4)...第十行:元组(A10: B10)——>每一个单元格对象

    print(sh["A3":"B10"])
    

    运行结果:

    ((<Cell 'Sheet'.A3>, <Cell 'Sheet'.B3>), (<Cell 'Sheet'.A4>, <Cell 'Sheet'.B4>), (<Cell 'Sheet'.A5>, <Cell 'Sheet'.B5>), (<Cell 'Sheet'.A6>, <Cell 'Sheet'.B6>), (<Cell 'Sheet'.A7>, <Cell 'Sheet'.B7>), (<Cell 'Sheet'.A8>, <Cell 'Sheet'.B8>), (<Cell 'Sheet'.A9>, <Cell 'Sheet'.B9>), (<Cell 'Sheet'.A10>, <Cell 'Sheet'.B10>))
    

    这种多层嵌套的形式,我们要想获得最里面单元格对象,就要用到双层for循环:

    for item in sh["A3":"B10"]:            #item表示每一行的单元格元组
        for cell in item:                  #cell表示每一行的每一个单元格对象
            print(cell)                    #打印出每个单元格对象
    

    运行结果:

    <Cell 'Sheet'.A3>
    <Cell 'Sheet'.B3>
    <Cell 'Sheet'.A4>
    <Cell 'Sheet'.B4>
    <Cell 'Sheet'.A5>
    <Cell 'Sheet'.B5>
    <Cell 'Sheet'.A6>
    <Cell 'Sheet'.B6>
    <Cell 'Sheet'.A7>
    <Cell 'Sheet'.B7>
    <Cell 'Sheet'.A8>
    <Cell 'Sheet'.B8>
    <Cell 'Sheet'.A9>
    <Cell 'Sheet'.B9>
    <Cell 'Sheet'.A10>
    <Cell 'Sheet'.B10>
    

    得到单元格对象就好办了,只需要单元格对象.value,我们就可以获取单元格值。试试按照excel中的形式打印,得到的结果看起来很美观:

    用enumerate包装一个可迭代对象,可以同时使用索引和迭代项,在迭代的同时获取迭代项所在位置时非常方便

    for index, item in enumerate(sh["A3":"B10"]):
        if index > 0:
            print("
    ")
        for cell in item:
            print(cell.value, end=" ")
    
    
    运行结果:
    2018-05-10 电影 
    
    hello world 小说 
    
    hi 数据 
    
    stop 美团 
    
    bike 花生 
    
    中国 电视 
    
    测试 连续剧 
    
    深圳 广告
    
  • 相关阅读:
    这年头学爬虫还就得会点 scrapy 框架
    【全栈之路】JAVA基础课程十_JAVA虚拟机(20190706v1.1)
    牛客练习赛61
    ERD图
    深入理解Java虚拟机-如何利用VisualVM对高并发项目进行性能分析
    阿里研究员吴翰清:世界需要什么样的智能系统?
    《深入理解 C# (第2版)》
    HtmlAgility 抓取网页上的数据
    abp(net core)+easyui+efcore实现仓储管理系统——入库管理之三存储过程(三十九)
    如何Tomcat完美访问web项目,无需配置“项目名”
  • 原文地址:https://www.cnblogs.com/python960410445/p/12608589.html
Copyright © 2011-2022 走看看