简体   繁体   English

如何使用谷歌表 api 随机化 python 中的范围?

[英]How to randomizeRange in python with google sheets api?

I'm trying to run this code:我正在尝试运行这段代码:

requests = {
    'randomizeRange': {
        'range': {
            'ranges': ['Sheet1!A3:A32']
        }
    }
}
request = sheet.batchUpdate(spreadsheetId=sheet_id, body=requests)
r = request.execute()
print(r)

But I get this error:但我收到此错误:

Invalid JSON payload received.收到无效的 JSON 负载。 Unknown name "randomizeRange": Cannot find field.未知名称“randomizeRange”:找不到字段。

What's wrong with this code?这段代码有什么问题?

I believe your goal is as follows.我相信你的目标如下。

  • You want to use RandomizeRangeRequest of Sheets API using googleapis for python.您想使用 python 的 googleapis 使用 Sheets API 的 RandomizeRangeRequest。

Modification points:修改点:

  • In this case, the request body is {"requests": [{"randomizeRange": {"range": {,,,}}}]} .在这种情况下,请求主体是{"requests": [{"randomizeRange": {"range": {,,,}}}]}
  • From your script, I thought that sheet might be service.spreadsheets() .根据您的脚本,我认为该sheet可能是service.spreadsheets()
  • And also, the range is required to be GridRange.而且,范围必须是 GridRange。
    • When the a1Notation of Sheet1:A3:A32 is converted to the GridRange, it becomes as follows.Sheet1:A3:A32的a1Notation转换为GridRange时,变成如下。

       "range": { "sheetId": sheet_id, # This is the sheet ID of "Sheet1". "startRowIndex": 2, "endRowIndex": 32, "startColumnIndex": 0, "endColumnIndex": 1, }

When these points are reflected in your script, it becomes as follows.当这些点反映在你的脚本中时,它就变成了下面这样。

Modified script:修改脚本:

spreadsheet_id = "###"  # Please set your Spreadsheet ID
sheet_id = "###"  # Please set your sheet ID. In your script, please set the sheet ID of "Sheet1".

service = build("sheets", "v4", credentials=creds) # Please use your script here.
sheet = service.spreadsheets()
requests = {
    "requests": [
        {
            "randomizeRange": {
                "range": {
                    "sheetId": sheet_id,
                    "startRowIndex": 2,
                    "endRowIndex": 32,
                    "startColumnIndex": 0,
                    "endColumnIndex": 1,
                }
            }
        }
    ]
}
sheet.batchUpdate(spreadsheetId=spreadsheet_id, body=requests).execute()
  • When this script is run, the cells "A3:A32" of "Sheet1" are randomized.运行此脚本时,“Sheet1”的单元格“A3:A32”将被随机化。

References:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM