首页 > 解决方案 > 从指向另一个单元格的单元格获取实际值

问题描述

我正在尝试创建一个脚本来处理谷歌电子表格,但有时,当我使用 commandval = worksheet.cell(1, 2).value时,实际值就像=M7,因此,它对脚本没有真正的价值。是否有任何可能的解决方法可以从“M7”单元格中获取内容并将其复制到我正在阅读的单元格中?

样品表在这里

示例代码:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']
spreadsheet_id = '1sfltKJ1-EBlXJReDSmb5KiqeNSXbHuuLH2d2O1_Qfyc'
credentials = ServiceAccountCredentials.from_json_keyfile_name('C:\credentials.json', scope)
client = gspread.authorize(credentials)
wb = client.open_by_key(spreadsheet_id)

ws = None
sheets = [s for s in wb.worksheets() if s.id == 0]
if sheets:
    ws = sheets[0]

values = ws.get_all_values(value_render_option='FORMULA')

print(values)

# if you run this code, you will see that for gspread, the stirng 'original_value' is only in the B2 cell.
# When the gspread module reads the D2 cell, it shows actually the formula, that is =B2
# Also, I need to used the param 'value_render_option='FORMULA'', because sometimes there is a hyperlink formula in the cell,
# so sometimes I need to read the real content of the cell.

# I hope you understand the formula

继续,如果你运行上面的代码,你会得到这个列表:

[['', '', '', ''], ['', 'original_value', '', '=B2']]

但预期的输出应该是:

[['', '', '', ''], ['', 'original_value', '', 'original_value']]

更新:

我已经为这个问题创建了一个解决方法,所以如果这对任何人都有用,代码将如下:

def column2number(col):
    num = 0
    for c in col:
        if c in string.ascii_letters:
            num = num * 26 + (ord(c.upper()) - ord('A')) + 1
    return num

values = ws.get_all_values(value_render_option='FORMULA')
for i in range(len(values)):
    for j in range(len(values[i])):
        # this will check a combination of any number of uppercase letters followed by any number of numbers, representing the column and the line, respectively.
        p = re.compile('^=[A-Z]+[0-9]+')
        try:
            # if the variable p is not null, we will retrieve the matched regex from the string, split it, and get only the letters.
            r = p.match(str(values[i][j])).group()
            output = re.split('(\d+)',r[1:])
            # this function 'column2number' will convert the column letters to its position numerically
            output[0] = column2number(output[0]) - 1
            output[1] = int(output[1]) - 1
            output[2] = i
            output.append(j)
            
            # the output is filled, respectivelly by: referenced column, referenced line, line where the content will be placed, column where the content will be placed

            values[i][j] = values[output[1]][output[0]]
        except AttributeError:
            pass
print(values)

此解决方法将仅替换引用公式,例如=M7M7 单元格中的现有内容。

标签: pythonpython-3.xgoogle-sheetsgoogle-sheets-apigspread

解决方案


我相信你的目标如下。

  • 您想使用 gspread 检索单元格值。
  • 您不想检索公式。

修改点:

  • 当我看到 ,when 的文档时get_all_values,当value_render_option='FORMULA'单元格有公式时检索公式。因此,当您要检索作为公式的单元格值时,请使用value_render_option='FORMATTED_VALUE'and value_render_option='UNFORMATTED_VALUE'
    • 当我看到gspread的脚本时,似乎FORMATTED_VALUE是默认值。参考

当以上几点反映到您的脚本时,它变成如下。

修改后的脚本:

从:
values = ws.get_all_values(value_render_option='FORMULA')
至:
values = ws.get_all_values()

或者

values = ws.get_all_values(value_render_option='UNFORMATTED_VALUE')

参考:

添加:

从您的回复中,我了解到您想在将超链接公式放入单元格时检索超链接公式。为此,我想提出以下脚本。

示例脚本:

values = ws.get_all_values()
formulas = ws.get_all_values(value_render_option='FORMULA')
for i, r in enumerate(formulas):
    for j, c in enumerate(r):
        if '=hyperlink' in c:
            values[i][j] = c
print(values)
  • 在此示例脚本中,检索值和公式,当=hyperlink包含在公式中时,检索公式。我认为这种方法可能很简单。

推荐阅读