欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python如何获取多个excel单元格的值

程序员文章站 2024-01-03 20:03:16
一. 获取多个单元格的值报错:AttributeError: 'tuple' object has no attribute 'value' 需要读取的sample.xlsx 代码读取的是A3:B10之间的单元格 运行结果: 二. 如何解决 上面报错信息是,元组对象没有属性"value",我们先来看 ......

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

需要读取的sample.xlsx
python如何获取多个excel单元格的值
代码读取的是a3:b10之间的单元格

from openpyxl import load_workbook

wb = load_workbook(r"d:\python_workshop\python6\study\sample.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("\n")
    for cell in item:
        print(cell.value, end=" ")


运行结果:
2018-05-10 电影 

hello world 小说 

hi 数据 

stop 美团 

bike 花生 

中国 电视 

测试 连续剧 

深圳 广告

上一篇:

下一篇: