Python gspread Hyperlink adds '

Question:

I want to add a Hyperlink to a cell. I’m using the following code:

cell_values = [1,'=HYPERLINK("' + some_url + '","' + some_text + '")',3]
for i, val in enumerate(cell_values):
  cell_list[i].value = val
worksheet.update_cells(cell_list)

What is printed into the cell:

'=HYPERLINK("someLink","someText")

The cell should be formatted as a Hyperlink, but the value of the cell is written with a ' in front of it, which destroys the use of the formula.

Asked By: Tanne

||

Answers:

I think you are using Excel’s built-in hyperlink function which should looks like

'=HYPERLINK("{}", "{}")'.format(link, "Link Name")

I recommend you use f-string or .format to insert variables into strings. I think in your code you used ' + some_url + ' which should be ''' + some_url + '''

Answered By: Zichzheng

I thought that the reason of your issue is due to value_input_option='RAW' as the default value. When I saw the document of gspread, it seems that value_input_option of update_cells(cell_list, value_input_option='RAW') is RAW as the default value. In this case, the value is put as the string. By this, the single quote is added to the top of character.

In order to put =HYPERLINK("someLink","someText") as the formula, please use the value of USER_ENTERED instead of RAW. So when your script is modified, please modify as follows.

From:

worksheet.update_cells(cell_list)

To:

worksheet.update_cells(cell_list, value_input_option='USER_ENTERED')

References:

  • update_cells(cell_list, value_input_option=’RAW’)
  • ValueInputOption
    • RAW: The values the user has entered will not be parsed and will be stored as-is.
    • USER_ENTERED: The values will be parsed as if the user typed them into the UI. Numbers will stay as numbers, but strings may be converted to numbers, dates, etc. following the same rules that are applied when entering text into a cell via the Google Sheets UI.
Answered By: Tanaike