【问题标题】:Example of request body for creating a google spreadsheet in specific google drive location via python API?通过 python API 在特定谷歌驱动器位置创建谷歌电子表格的请求正文示例?
【发布时间】:2020-08-05 16:29:21
【问题描述】:

尝试使用 python API 在谷歌驱动器上的特定位置创建电子表格,但 the docs 关于如何执行此操作省略了任何关于 request body 究竟是什么样子的具体示例。

最终,拥有一个带有标题和单行值的 pandas 数据框,并尝试在谷歌驱动器中创建一个看起来像...的电子表格

------------------
header1 | value1 |
------------------
header2 | value2 |
------------------
header3 | value3 |
------------------
header4 | value4 |
------------------
header5 | value5 |
------------------

第 1、2 和 5 行受到保护。

在查看此类请求的 JSON 正文的文档时,我遇到的一些具体问题是……

  1. 我可以使用什么作为spreadsheetId?命名冲突会发生什么?文档似乎没有关于什么这是或可能是的任何信息/示例。
  2. 我怎么知道spreadsheetUrl 使用什么?有默认值吗?这到底是什么意思/看起来像什么?
  3. 请求正文中的某些小节似乎需要冗余信息(例如sheetId)。这有必要吗/我可以留空吗?
  4. 我如何知道/指定 Google 驱动器中的哪个位置将要创建此工作表(我有一个特定的 dir 路径,我想在其中创建这些电子表格)?

这是我目前构建的请求正文(注意,这里我只是尝试以 row1=header, row2=values 的常规表格格式将数据放入电子表格) ...

df = <some dataframe>
HEADER = list(df.columns)
VALUES = df.values.tolist()[0]  # first row of values from dataframe

# building request body for API spreadsheets.create request
request_body = {
  "spreadsheetId": VALUES[0],  # this is a UUID for the data row in the pandas dataframe
  "properties": {
    "title": f"{DATANAME}__{VALUES[0]}",
  },
  "sheets": [
    {
        "properties": {
            "sheetId": 1,
            "title": DATANAME
        },
        "data": [
            {
              "startRow": 1,
              "startColumn": 1,
              "rowData": [
                {
                    "values": [
                        HEADER, # list if values
                        VALUES  # list of values
                    ]
                }
              ],
            }
        ],
        "protectedRanges": [
            {
              "protectedRangeId": integer, # what even is this?
              "range": {
                  {
                      "sheetId": 1, # do I really need to specify the sheetId again here?
                      "startRowIndex": 1,
                      "endRowIndex": 3,
                      "startColumnIndex": 1,
                      "endColumnIndex": 3
                  }
              },
              "description": "This is a metadata field and should not be edited",
              "warningOnly": False,
            },
            {
              "protectedRangeId": integer, # what even is this?
              "range": {
                  {
                      "sheetId": 1,
                      "startRowIndex": 5,
                      "endRowIndex": 6,
                      "startColumnIndex": 5,
                      "endColumnIndex": 6
                  }
              },
              "description": "This is a metadata field and should not be edited",
              "warningOnly": False,
            }
        ]
    }
  ],
  "spreadsheetUrl": string,
}

这里有更多经验的人可以向我展示一个示例,说明在这种情况下实际工作的请求正文会是什么样子(以及到目前为止我构建的内容有什么问题)吗?以及回答上面一些更具体的问题?

还有其他地方可以查看链接文档的更多示例/信息吗?

【问题讨论】:

  • 我必须为我糟糕的英语水平道歉。我可以问你关于你的问题吗?在您的问题中,有以下 7 个问题? 1. 我可以使用什么作为电子表格 ID?命名冲突会发生什么?文档似乎没有关于这是什么或可以是什么的任何信息/示例。 2. 我怎么知道使用什么电子表格网址?有默认值吗?这甚至意味着什么/看起来像什么? 3. 请求正文中的某些小节似乎需要冗余信息(例如 sheetId)。这有必要吗/我可以留空吗?
  • 4.我如何知道/指定将在 google 驱动器中创建此工作表的位置(我有一个特定的目录路径,我想在其中创建这些电子表格)? 5. 这里有更多经验的人可以给我一个例子,说明在这种情况下实际工作的请求主体是什么样的(以及到目前为止我所构建的有什么问题)吗? 6. 以及回答上面一些更具体的问题? 7. 是否有其他地方可以查看链接文档的更多示例/信息?
  • 作为附加问题,我可以问一下您用于向 Sheets API 请求的库吗?而且,就您而言,我认为需要使用 Drive API。那么请问您是否可以使用 Sheets API 和 Drive API?
  • @Tanaike 是的,有 7 个问题(除了问题 6 只是参考上一个问题 1-4)。我只使用 google API 参考文档 (developers.google.com/sheets/api/quickstart/…) 中引用的标准 google API 库(主要是因为我不能使用服务帐户凭据,因为这将是我们组织电子邮件域之外的电子邮件)。我确实拥有对 Sheets 和 Drive API 的 API 访问权限。
  • 感谢您的回复。我可以理解您用于请求 Sheets API 的模块,您也可以使用 Drive API 和 Sheets API。我认为在这种情况下,可以将电子表格创建到特定文件夹。但是,我为我糟糕的英语水平深表歉意。不幸的是,来自there are 7 questions (except question 6 is just referencing the previous question 1-4).,我无法理解您的问题。我可以问你问题的细节吗?我想通过正确理解您的问题来思考解决方案。对此我深表歉意。

标签: python google-sheets google-sheets-api


【解决方案1】:

从对问题 here 和 here 的回答来看,这就是我目前在 Drive 中创建电子表格并添加值和受保护范围以保护元数据值的方式(通过 python API 客户端)。

基本上,由于spreadsheets.create() 方法无法指定 Drive 位置,我必须使用 Drive api 在指定位置创建电子表格(通过 Drive 文件夹 ID(您在 Drive 文件夹中看到的 ID 字符串) URL)),从请求响应中获取分配的电子表格 ID,构建一系列 Sheets api 请求,然后通过spreadsheets.batchUpdate 发送这些请求(引用创建的电子表格的 ID)

# getting data from pandas dataframe for writing
df = df.fillna("")
HEADER = [str(c) for c in df.columns]
VALUES = [str(v) for v in df.values.tolist()[0]]
data = [HEADER, VALUES]
print(HEADER, VALUES)

# using Drive API to create the Spreadsheet in specified Drive location
drive = build('drive', 'v3', credentials=creds)
file_metadata = {
    'name': 'sampleName',
    'parents': ['### folderId ###'],
    'mimeType': 'application/vnd.google-apps.spreadsheet',
}
res = drive.files().create(body=file_metadata).execute()
print(res)
SPREADSHEET_ID = res['id']

# building request object
requests = [
    {  
        "appendCells":
        {
            "sheetId": 0,
            "rows": [
                {   # need to build the individual cell value objects for the request
                    "values": [{"userEnteredValue": {"stringValue": v}} for v in HEADER],
                },
                {
                    "values": [{"userEnteredValue": {"stringValue": v}} for v in VALUES],
                }
            ],
            "fields": "*"
         },
    },
    {  
        "addProtectedRange": {
            # protecting header fields
            "protectedRange": {
                "range": {
                    "sheetId": 0,  # sheets are indexed from 0
                    "startRowIndex": 0,
                    "endRowIndex": 1,  # pretty sure the endIndexes are exclusive
                    "startColumnIndex": 0,
                    "endColumnIndex": len(HEADER)
                },
                "description": "Do not edit this header data",
                "warningOnly": False,
            }
        }
    },
    {
        "addProtectedRange": {
            # protecting metadata values
            "protectedRange": {
                "range": {
                    "sheetId": 0,  # sheets are indexed from 0
                    "startRowIndex": 0,
                    "endRowIndex": 2,  # pretty sure the endIndexes are exclusive
                    "startColumnIndex": 0,
                    "endColumnIndex": 2
                },
                "description": "This is a metadata field and should not be edited",
                "warningOnly": False,
            }
        }
    },
    {
        "addProtectedRange": {
            # protecting metadata values
            "protectedRange": {
                "range": {
                    "sheetId": 0,  # sheets are indexed from 0
                    "startRowIndex": 0,
                    "endRowIndex": 2,  # pretty sure the endIndexes are exclusive
                    "startColumnIndex": 8,
                    "endColumnIndex": 10
                },
                "description": "This is a metadata field and should not be edited",
                "warningOnly": False,
            }
        }
    }
]

# do the batch updates on the Spreadsheet
request_body = {"requests": requests}
assert "requests" in request_body.keys()
assert isinstance(request_body["requests"], typing.List)
sheets = discovery.build('sheets', 'v4', credentials=credentials)
request = sheets.spreadsheets() \
            .batchUpdate(spreadsheetId=SPREADSHEET_ID, body=request_body)
request.execute()
print(request)

参考资料: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#examples https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#appendcellsrequest https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#addprotectedrangerequest

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多