使用 gspread,尝试为一个字符串着色
Using gspread, trying to color one string
在 google 工作表中,我试图找到类似“find”的字符串并突出显示该字符串。请看下面。
cell_list = worksheet.findall("查找")
我相信你的目标如下。
- 您想使用
findall
. 在 Google Spreadsheet 上搜索来自 sheet 的文本
- 您想更改搜索到的单元格的字体颜色。
- 您想使用 python 的 gspread 实现此目的。
在这种情况下,下面的示例脚本怎么样?
示例脚本:
client = gspread.authorize(credentials) # Please use your authorization script.
spreadsheetId = "###" # Please set the Spreadsheet ID.
sheetName = "Sheet1" # Please set the sheet name you want to search.
search_text = "find" # Please set the search text.
color = {"red": 1, "green": 0, "blue": 0} # Please set the color. In this sample, the red color is used.
spreadsheet = client.open_by_key(spreadsheetId)
worksheet = spreadsheet.worksheet(sheetName)
cell_list = worksheet.findall(search_text)
if cell_list != []:
sheet_id = worksheet.id
reqs = []
for e in cell_list:
reqs.append({
"updateCells": {
"range": {
"sheetId": sheet_id,
"startRowIndex": e._row - 1,
"endRowIndex": e._row,
"startColumnIndex": e._col - 1,
"endColumnIndex": e._col
},
"rows": [
{
"values": [
{
"userEnteredFormat": {
"textFormat": {
"foregroundColor": color
}
}
}
]
},
],
"fields": "userEnteredFormat.textFormat.foregroundColor"
}
})
res = spreadsheet.batch_update({"requests": reqs})
- 当这个脚本是运行时,
search_text
的值是从sheet中搜索的。并且,搜索到的单元格的字体颜色已更改。
参考:
最新版本的gspread
有专门的单元格格式化方法。无需编写您自己的请求。它还具有将单元格索引转换为 A1 表示法的方法。你可以简单地做:
range = rowcol_to_a1(e.row, e.col):
worksheet.format(range, {"foregroundColor": color})
在 google 工作表中,我试图找到类似“find”的字符串并突出显示该字符串。请看下面。
cell_list = worksheet.findall("查找")
我相信你的目标如下。
- 您想使用
findall
. 在 Google Spreadsheet 上搜索来自 sheet 的文本
- 您想更改搜索到的单元格的字体颜色。
- 您想使用 python 的 gspread 实现此目的。
在这种情况下,下面的示例脚本怎么样?
示例脚本:
client = gspread.authorize(credentials) # Please use your authorization script.
spreadsheetId = "###" # Please set the Spreadsheet ID.
sheetName = "Sheet1" # Please set the sheet name you want to search.
search_text = "find" # Please set the search text.
color = {"red": 1, "green": 0, "blue": 0} # Please set the color. In this sample, the red color is used.
spreadsheet = client.open_by_key(spreadsheetId)
worksheet = spreadsheet.worksheet(sheetName)
cell_list = worksheet.findall(search_text)
if cell_list != []:
sheet_id = worksheet.id
reqs = []
for e in cell_list:
reqs.append({
"updateCells": {
"range": {
"sheetId": sheet_id,
"startRowIndex": e._row - 1,
"endRowIndex": e._row,
"startColumnIndex": e._col - 1,
"endColumnIndex": e._col
},
"rows": [
{
"values": [
{
"userEnteredFormat": {
"textFormat": {
"foregroundColor": color
}
}
}
]
},
],
"fields": "userEnteredFormat.textFormat.foregroundColor"
}
})
res = spreadsheet.batch_update({"requests": reqs})
- 当这个脚本是运行时,
search_text
的值是从sheet中搜索的。并且,搜索到的单元格的字体颜色已更改。
参考:
最新版本的gspread
有专门的单元格格式化方法。无需编写您自己的请求。它还具有将单元格索引转换为 A1 表示法的方法。你可以简单地做:
range = rowcol_to_a1(e.row, e.col):
worksheet.format(range, {"foregroundColor": color})