Google Sheet API获取数据验证

2024-10-03 23:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我当前的电子表格设置数据验证规则。有一件事可以帮助我从我已经设置的数据验证规则(在电子表格UI或API调用中)中查看JSON中的规则。在

例子。在

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调用来查看这些单元格范围内的数据验证呢?如果我在电子表格中设置数据验证规则,并且我想看看google是如何解释它们的,这一点很有用。我在通过API设置复杂的数据验证时遇到了很多麻烦。在

谢谢你


Tags: 数据apiidjsonui规则requestrange
2条回答

要只获得给定电子表格的“数据验证”组件,只需在调用^{}时请求相应的字段:

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对象和sheetId和{}对象。在

您可以使用Google API Explorer以交互方式确定适当的有效“字段”规范,并进一步检查响应: https://developers.google.com/apis-explorer/#p/sheets/v4/sheets.spreadsheets.get

有关“fields”说明符如何工作的更多信息,请阅读文档:https://developers.google.com/sheets/api/guides/concepts#partial_responses

(对于某些写请求,字段规范不是可选的,因此确定如何有效地使用它们最符合您的利益。)

我想我找到了答案。IncludeGridData=True在你的spreadsheet().get

from pprint import pprint    
response = service.spreadsheets().get(
        spreadsheetId=SPREADSHEETID, fields='*',
        ranges='InputWorking!A2:A',includeGridData=True).execute()

你得到了一个怪物的数据结构。所以要想了解你所能做的第一个数据。在

^{pr2}$

相关问题 更多 >