我正在编写一个 Python 脚本来使用 Google Sheets API 更新 Google Sheets 文档,并且我需要在单个单元格中添加多个超链接以及一些消息。但是,我很难实现这一目标。这就是我正在尝试做的事情:
我有一个 Python 脚本,可以使用 Google Sheets 文档中的超链接更新特定单元格。超链接的格式应该是每个链接后面都跟有一条消息。例如,我希望单元格包含两个超链接,每个超链接都有不同的消息,并且我希望它们看起来像这样:
Google Drive(指向“https://drive.google.com/”的超链接)
Amazon Drive(指向“https://www.amazon.com”的超链接)
我尝试在单元格数据中使用 HYPERLINK 函数,并使用 CHAR(10) 插入换行符,但它没有按预期工作。单元格显示文本,但链接不可点击。
这是我正在使用的Python代码:
def list_problems(percentage_difference, asin, col_name, message="OK"):
LIST_PROBLEMS = 'List Problems'
worksheet = gc.open_by_key(spreadsheet_id).worksheet(LIST_PROBLEMS)
cell = worksheet.find(asin)
hyperlink_url1 = "https://drive.google.com/"
hyperlink_url2 = "https://www.amazon.com" # Replace with the Amazon link
text1 = "Google Drive"
text2 = "Amazon Drive"
cell_format = {
"backgroundColor": {
"red": 183/255,
"green": 225/255,
"blue": 205/255
}
}
if percentage_difference >= 10:
cell_data = (
f'=HYPERLINK("{hyperlink_url1}", "{text1}") & " | " & HYPERLINK("{hyperlink_url2}", "{text2}")'
)
else:
cell_data = (
f'=HYPERLINK("{hyperlink_url1}", "{text1}") & " | " & HYPERLINK("{hyperlink_url2}", "{text2}")'
)
worksheet.update(f"{ColumnsRange[col_name]}{cell.row}", "", value_input_option='USER_ENTERED') # Clear the cell
worksheet.update(f"{ColumnsRange[col_name]}{cell.row}", cell_data, value_input_option='USER_ENTERED')
# Apply cell formatting
worksheet.format(f"{ColumnsRange[col_name]}{cell.row}", cell_format)
这是我运行代码时在工作表中的样子。 Google Sheet Cell 不是超链接...
我相信您的目标如下。
根据您的情况,以下示例脚本怎么样?
在此示例中,使用 gspread 将值放入 Google 电子表格上“Sheet1”的单元格“A1”中。
import gspread
client = # Please use your gspread client.
spreadsheetId = "###" # Please set your Spreadsheet ID.
sheetName = "Sheet1" # Please set your sheet name.
# These values are from your showing script.
hyperlink_url1 = "https://drive.google.com/"
hyperlink_url2 = "https://www.amazon.com"
text1 = "Google Drive"
text2 = "Amazon Drive"
cell_format = {"backgroundColor": {"red": 183/255, "green": 225/255, "blue": 205/255}}
spreadsheet = client.open_by_key(spreadsheetId)
sheet = spreadsheet.worksheet(sheetName)
obj = [{"t": text1, "u": hyperlink_url1}, {"t": text2, "u": hyperlink_url2}]
text = "\n".join([e["t"] for e in obj])
requests = [
{
"updateCells": {
"rows": [
{
"values": [
{
"userEnteredValue": {"stringValue": text},
"textFormatRuns": [{"format": {"link": {"uri": e["u"]}}, "startIndex": text.find(e["t"])} for e in obj],
"userEnteredFormat": cell_format
}
]
}
],
"range": {"sheetId": sheet.id, "startRowIndex": 0, "endRowIndex": 1, "startColumnIndex": 0, "endColumnIndex": 1},
"fields": "userEnteredValue,textFormatRuns,userEnteredFormat"
}
}
]
spreadsheet.batch_update({"requests": requests})
运行该脚本,得到如下结果。您可以在“A1”中看到包含多个超链接的单元格值。