我正在尝试为我当前的电子表格设置数据验证规则。对我有帮助的一件事是能够从我已经设置的数据验证规则中查看 JSON 中的规则(在电子表格 UI 中或在 API 调用中)。
例子。
request = {
"requests": [
{
"setDataValidation": {
"range": {
"sheetId": SHEET_ID,
"startRowIndex": 1,
"startColumnIndex": 0,
"endColumnIndex":1
},
"rule": {
"condition": {
"type": "BOOLEAN"},
"inputMessage": "Value MUST BE BOOLEAN",
"strict": "True"
}
}
}
]
}
service.spreadsheets().batchUpdate(spreadsheetId=SPREADSHEET_ID body=request).execute()
但是我使用哪些 API 调用来查看这些单元格范围的数据验证?如果我在电子表格中设置数据验证规则并且我想查看谷歌如何解释它们,这将很有用。我在通过 API 设置复杂的数据验证时遇到了很多麻烦。
谢谢
请您参考如下方法:
要仅获取给定电子表格的“数据验证”组件,您只需在对 spreadsheets.get 的调用中请求适当的字段即可。 :
service = get_authed_sheets_service_somehow()
params = {
spreadsheetId: 'your ssid',
#range: 'some range',
fields: 'sheets(data/rowData/values/dataValidation,properties(sheetId,title))' }
request = service.spreadsheets().get(**params)
response = request.execute()
# Example print code (not tested :p )
for sheet in response['sheets']:
for range in sheet['data']:
for r, row in enumerate(range['rowData']):
for c, col in enumerate(row['values']):
if 'dataValidation' in col:
# print "Sheet1!R1C1" & associated data validation object.
# Assumes whole grid was requested (add appropriate indices if not).
print(f'\'{sheet["properties"]["title"]}\'!R{r}C{c}', col['dataValidation'])
通过指定字段,includeGridData 不需要从您请求的范围中获取每个单元格的数据。通过不提供范围,我们以整个文件为目标。此特定字段规范请求 rowData.values.dataValidation 对象以及 properties 对象的 sheetId 和 title,对于电子表格中的每张纸。
您可以使用 Google APIs Explorer 以交互方式确定适当的有效“字段”规范,并另外检查响应: https://developers.google.com/apis-explorer/#p/sheets/v4/sheets.spreadsheets.get
有关“字段”说明符如何工作的更多信息,请阅读文档:https://developers.google.com/sheets/api/guides/concepts#partial_responses
(对于某些写入请求,字段规范不是可选的,因此确定如何有效地使用它们符合您的最佳利益。)
