
我正在使用http://pygsheets.readthedocs.io/en/latest/index.html,一个围绕google sheets api v4的包装器。我对使用google-sheets api v4设置条件格式很感兴趣。我尝试使用一个自定义公式来根据行中"Q“列的值突出显示一行。如果Q列包含'TRASH',我想将行着色为红色。
当我浏览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.">我做错了什么?
发布于 2017-02-22 20:16:28
在Json有效负载return {"requests": [中,您不需要密钥requests,因为在sh_batch_update中,它已经将其包装在请求中。请看一下worksheet.py中的delete_cols实现,以查看用法示例。
所以实际上你可以这样做,
return {
"addConditionalFormatRule": {
"rule": {此外,您不需要在此处传递范围,gc.sh_batch_update(ssheet.id,cfr1(ws.id),'A1:R8')字段参数决定要返回的响应字段
https://stackoverflow.com/questions/42381184
复制相似问题