Getting cell data from openpyxl looped rows
Question:
I have some code to create tuples from OpenPyXL in a python script that looks like:
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50)
print(row)
Which returns
(<Cell 'States'.A2>, <Cell 'States'.B2>)
(<Cell 'States'.A3>, <Cell 'States'.B3>)
...
(<Cell 'States'.A50>, <Cell 'States'.B50>)
I would like to pull the values from the ‘A-column’ and the ‘B-column’ by using cell.value and further splitting the ‘B-column’ by a comma delimited value (ex. 7,100 or 100,7) then adding the values to a dictionary that would look like:
StatesPriority = {
A2 : (B2.ValueBeforeComma, B2.ValueAfterComma)
A3 : (B3.ValueBeforeComma, B3.ValueAfterComma)
...
A50 : (B50.ValueBeforeComma, B50.ValueAfterComma)
}
However, I am more concerned about the OpenPyXL function of getting values from a returned tuple. I think I can figure out splitting values by commas on my own with a little bit of time.
Python Version: 3.6.3
OpenPyXL Version: 2.4.9
All help is appreciated!
Answers:
row
is a tuple with two elements, therefore you can unpack it during assignment:
StatesPriority = {}
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50)
cell_a, cell_b = row
StatesPriority[cell_a.value] = (tuple(cell_b.value.split(','))
After some research, I believe the new method is to use values_only=True like below :
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50, values_only=True)
print(row)
I have some code to create tuples from OpenPyXL in a python script that looks like:
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50)
print(row)
Which returns
(<Cell 'States'.A2>, <Cell 'States'.B2>)
(<Cell 'States'.A3>, <Cell 'States'.B3>)
...
(<Cell 'States'.A50>, <Cell 'States'.B50>)
I would like to pull the values from the ‘A-column’ and the ‘B-column’ by using cell.value and further splitting the ‘B-column’ by a comma delimited value (ex. 7,100 or 100,7) then adding the values to a dictionary that would look like:
StatesPriority = {
A2 : (B2.ValueBeforeComma, B2.ValueAfterComma)
A3 : (B3.ValueBeforeComma, B3.ValueAfterComma)
...
A50 : (B50.ValueBeforeComma, B50.ValueAfterComma)
}
However, I am more concerned about the OpenPyXL function of getting values from a returned tuple. I think I can figure out splitting values by commas on my own with a little bit of time.
Python Version: 3.6.3
OpenPyXL Version: 2.4.9
All help is appreciated!
row
is a tuple with two elements, therefore you can unpack it during assignment:
StatesPriority = {}
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50)
cell_a, cell_b = row
StatesPriority[cell_a.value] = (tuple(cell_b.value.split(','))
After some research, I believe the new method is to use values_only=True like below :
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50, values_only=True)
print(row)