Getting cell data from openpyxl looped rows

python excel python-3.x tuples openpyxl

612 观看

1回复

13 作者的声誉

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!

作者: Bill 的来源 发布者: 2017 年 12 月 27 日

回应 1


1

59043 作者的声誉

决定

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(','))
作者: Mike Müller 发布者: 2017 年 12 月 27 日
32x32