从指向另一个单元格的单元格获取实际值

Get real value from a cell pointing to another cell

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

样本 sheet 是 here

示例代码:

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)

此解决方法只会用 M7 单元格中的现有内容替换 =M7 等引用公式。

我相信你的目标如下。

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

修改点:

  • 看到get_all_values的文档时,用value_render_option='FORMULA'的时候,当单元格有公式的时候,就检索公式。因此,当您要检索作为公式的单元格值时,请使用 value_render_option='FORMATTED_VALUE'value_render_option='UNFORMATTED_VALUE'
    • 看gspread的脚本时,好像默认的是FORMATTED_VALUERef

当以上几点反映到你的脚本中,就变成了下面这样。

修改后的脚本:

从:
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 时,检索公式。我认为这种方法可能很简单。