I'm working with http://pygsheets.readthedocs.io/en/latest/index.html a wrapper around the google sheets api v4. I am interested in setting conditional formatting using the google-sheets-api v4. I'm trying to use a custom formula to highlight a row based on the value of the "Q" column in the row. if the q column contains 'TRASH', I want to colour the row red.
As I look through the pygheets library in https://github.com/nithinmurali/pygsheets/blob/master/pygsheets/client.py I came across, which I believe is the way to send this request:
# @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)
Further, in https://developers.google.com/sheets/api/samples/conditional-formatting#add_a_custom_formula_rule_to_a_range, an example is given on how to send a custom request. Based on this I have:
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')
but I'm getting:
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.">
What am I doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…