I. Getting values for multiple cells Error: Attributeerror: ' Tuple ' object has no attribute ' value '
Sample.xlsx that need to be read
The code reads the cells between the A3:B10
fromOpenpyxlImportLOAD_WORKBOOKWB= Load_workbook (r"D:\python_workshop\python6\study\sample.xlsx") SH= wb["Sheet"]Print(sh["A3":"B10"].value) Run Result: Traceback (most recent call last): File"d:/python_workshop/python6/study/demo.py", line 8,inch<module>Print(sh["A3":"B10"].value)attributeerror: ' tuple ' object has no attribute ' value '
two. How to resolve
The above error message is that the tuple object does not have the attribute "value", we first look at print (sh["A2": "B10"]), get a tuple, more interesting is that each item in the tuple is also a tuple, the tuple is stored in each row of the Cell object: the equivalent of a tuple ( A3:B10)--third row: tuples (a3:b3), line Fourth: tuples (A4:B4) ... Line tenth: tuples (A10:B10)--each Cell object
Print(sh["A3":"B10"]) operation Result: ((<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>))
This form of multi-layered nesting, we want to get the innermost cell object, we need to use a double for loop:
forIteminchsh["A3":"B10"]:#item represents the cell tuple for each row forCellinchItem#Cell represents each cell object for each row Print(cell)#print out each cell objectOperation Result:<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>
It's good to get the cell object, just the Cell object. Value, we can get the cell value. Try printing in Excel, and the results look good:
#wrapping an iterative object with enumerate, you can use indexes and iterations at the same time, and it is convenient to get the position of the iteration at the same time. forIndex, iteminchEnumerate (sh["A3":"B10"]): ifIndex > 0: Print("\ n") forCellinchItem:Print(Cell.value, end=" ") operation Result:2018-05-10movie Hello World novel Hi data stop US Regiment bike peanut China TV Test series Shenzhen advertising
How Python gets the values of multiple Excel cells