我正在使用http://pygsheets.readthedocs.io/en/latest/index.html google sheet api v4 的包装器。我有兴趣使用 google-sheets-api v4 设置条件格式。我正在尝试使用自定义公式根据行中“Q”列的值突出显示一行。如果 q 列包含“垃圾”,我想将行着色为红色。
当我查看https://github.com/nithinmurali/pygsheets/blob/master/pygsheets/client.py中的 pygheets 库时,我遇到了,我相信这是发送此请求的方式:
# @TODO use batch update more efficiently
def sh_batch_update(self, spreadsheet_id, request, fields=None, batch=False):
if type(request) == list:
body = {'requests': request}
else:
body = {'requests': [request]}
final_request = self.service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body,
fields=fields)
return self._execute_request(spreadsheet_id, final_request, batch)
此外,在https://developers.google.com/sheets/api/samples/conditional-formatting#add_a_custom_formula_rule_to_a_range中,给出了如何发送自定义请求的示例。基于此,我有:
import tkinter as tk
import tkFileDialog
import pygsheets
def cfr1(sheetId):
# Apply to range: A1:R
# Format cells if...: Custom formula is
# (formula:) =$Q1="TRASH"
return {"requests": [
{
"addConditionalFormatRule": {
"rule": {
"ranges": [
{
"sheetId": sheetId,
"startColumnIndex": 'A',
"endColumnIndex": 'R',
"startRowIndex": 1,
"endRowIndex": 8
}
],
"booleanRule": {
"condition": {
"type": "CUSTOM_FORMULA",
"values": [
{
"userEnteredValue": '=$Q1="TRASH"'
}
]
},
"format": {
"backgroundColor": {
"red": 1.0
# "green": 0.0,
# "blue": 0.0
}
}
}
},
"index": 0
}
}
]
}
root = tk.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
print file_path
file_name = file_path.split('/')[-1]
print file_name
file_name_segments = file_name.split('_')
spreadsheet = file_name_segments[0]
worksheet = file_name_segments[1]+'_'+file_name_segments[2]
print worksheet
print spreadsheet
gc = pygsheets.authorize(outh_file='client_secret_xxx.apps.googleusercontent.com.json')
a =gc.list_ssheets()
wb_list = [d['name'] for d in a]
print wb_list
if spreadsheet not in wb_list:
print "Doesn't exist .."
else:
ssheet = gc.open(spreadsheet)
print ssheet.title
print 'ws '+worksheet
ws = ssheet.worksheet('title',worksheet)
gc.sh_batch_update(ssheet.id,cfr1(ws.id),'A1:R8')
但我得到:
googleapiclient.errors.HttpError: <HttpError 400 when requesting htps://sheets.googleapis.com/v4/spreadsheets/1Ypb_P**********pFt_SE:batchUpdate?fields=A1%3AR
8&alt=json returned "Invalid JSON payload received. Unknown name "requests" at 'requests[0]': Cannot find field.">
我究竟做错了什么?