5

通过使用 GSpread,我从谷歌电子表格返回了一系列单元格,该电子表格的所有元素如下所示:

<Cell R1C1 'Sandero'>

我知道如何从这里获取单元格值:

cell.value

但我也想单独获取地址(在这种情况下为 R1C1)。如果我能以 (1,1) 格式获得它,它必须是 (R1,C1) 甚至更好(也许通过使用字典?)

你看我也需要地址,因为我稍后会用这些值声明一个图表。

我正在使用 Python 2.7 和最新的 Gspread 库。

任何帮助将不胜感激。

4

2 回答 2

6

获取单元格坐标的最佳方法是使用单元格的实例属性rowcol. 这样您的代码可以简化为:

for cell in cell_list:
    print cell.value
    print "Row:", cell.row, "Column:", cell.col

要获得一个元组,只需将其包裹在括号中:(cell.row, cell.col)

由于我是 gspread 的作者,因此我更新了库页面以明确如何获取单元格的坐标。感谢您指出缺失的部分。

于 2012-12-25T11:58:50.007 回答
0

几个小时后,我设法自己完成了肮脏的工作。

所以我有从已经打开的谷歌电子表格获得的单元格范围内的数据:

cell_list = worksheet.range('A1:J8')

这包含<Cell R1C1 'Sandero'>但也<Cell R1C2 '23'>等等。

现在,为了从<Cell R1C1零件中获取稍后在项目中用于创建图形的坐标 (1,1),我意识到最好的方法是这样的:

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. 

然后必须小心将我的坐标引用为int(cella[0])int(cella[1])因为我将它们作为字符串从re.findall(r'\d+',str(cell))

我相信我的解决方案非常混乱且过于复杂,但至少它有效。我仍在等待该堆栈溢出,所以我希望有人有更好的主意。

于 2012-12-19T21:05:41.593 回答