问题
By using GSpread I have a range of cell's returned from a google spreadsheet that has all its elements something like this:
<Cell R1C1 'Sandero'>
I know how to get from here the cell value:
cell.value
but I would also like to get the address (R1C1 in this case) separately. It would have to be (R1,C1) or even better if I can get it in (1,1) format (maybe by using a dictionary?)
You see I need the address as well because I will later declare a graph with these values.
I'm using Python 2.7 and latest Gspread library.
Any help would be greately appreciated.
回答1:
The best way to get a cell's coordinates is by using the cell's instance properties row
and col
. This way your code can be simplified to this:
for cell in cell_list:
print cell.value
print "Row:", cell.row, "Column:", cell.col
To get a tuple, just wrap it in parenthesis: (cell.row, cell.col)
.
Since I'm the author of gspread, I've updated the library page to make it clear how to get a cell's coords. Thanks for pointing out the missing part.
回答2:
After many hours I managed to get the dirty work done by myself.
So I have the data in range of cells obtained from a google spreadsheet already opened:
cell_list = worksheet.range('A1:J8')
This contains <Cell R1C1 'Sandero'>
but also <Cell R1C2 '23'>
and so on.
Now in order to get from the <Cell R1C1
part the coordinates (1,1) that I would use to create a graph later on in my project I realized the best way is like this:
for cell in cell_list: # will check all elements of the worksheet range A1:J8
print cell # for example at one point this is <Cell R1C1 'Sandero'>
print cell.value # Sandero
cella = re.findall(r'\d+',str(cell)) # will take only numbers from <Cell R1C1 'Sandero'>
print cella[:2] # will give you the first two elements of list cella.
#In this case '1','1'. This is exactly what I need.
# to specify [:2] it's important if it would be <Cell R1C2 '23'>.
# Otherwise cella would return '1','2','23'. Nasty.
# I need only coordinates to use them as index in graf.
Then have to be careful to refer to my cordinates as int(cella[0])
and int(cella[1])
because I had them as strings from re.findall(r'\d+',str(cell))
I believe my solution is very messy and overcomplicated but at least it works. I'm still waiting for that stack to overflow so I hope someone has a better idea.
来源:https://stackoverflow.com/questions/13949540/gspread-or-such-help-me-get-cell-coordinates-not-value