使用 Google API 通过 Python 在 Google 工作表中创建新标签

Creating New Tabs via Python in Google Sheets using Google API

我需要通过 Python 为集合中的每个值创建一个选项卡。我已经使用 Google API 成功连接到 Google 表格,并且能够更新它。我一直无法弄清楚如何通过为集合中的每个唯一值创建每个选项卡来进行迭代。我的问题是我想用唯一值动态命名每个选项卡,这导致了错误。

唯一值设置示例:col1 = {abc,def,ghi}

示例代码:

import gspread
import csv
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import os
from apiclient import discovery
from google.oauth2 import service_account


scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
         "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]

credentials = ServiceAccountCredentials.from_json_keyfile_name('file.json', scope)
client = gspread.authorize(credentials)
sheets_service = discovery.build('sheets', 'v4', credentials=credentials)
drive_service = discovery.build('drive', 'v3', credentials=credentials)
spreadsheet = client.open('sheetname')


col1 = set()

with open('test.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',', skipinitialspace=True)        
    for row in csv_reader:
        col1.add(row[1])

for val in col1:
    spreadsheet = {
        'properties': {
            'title': "'"+val+"'"
        }
    }

    creation_response = sheets_service.spreadsheets().create(body=spreadsheet,
      fields=val).execute()

    spreadsheet_id = creation_response.get(val)   

错误:

  File "", line 41, in <module>
    creation_response = sheets_service.spreadsheets().create(body=spreadsheet,
  File "", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Python\Python39\lib\site-packages\googleapiclient\http.py", line 935, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets?fields=abc&alt=json returned 
"Request contains an invalid argument.". 
Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': 
[{'field': 'abc', 'description': "Error expanding 'fields' parameter. 
Cannot find matching fields for path 'abc'."}]}]">

问题:

您未在 fields 处提供有效值。

解释:

fields 是一个可选的请求参数,可用于设置您希望 return 编辑电子表格中的哪些信息。因此,您可以设置为 fields 的值非常有限。

abc 不是 Spreadsheet 中的现有字段,这导致请求无效。

解决方案:

您可以执行以下操作之一,具体取决于您想要执行的操作:

  • 如果要return特定字段,请指定存在于spreadsheet resource中的一个或多个(comma-separated)字段(嵌套字段为dot-separated或内部括号)。
  • 设置fields*到return所有字段。
  • 如果您想 return 此资源的所有默认响应字段,请不要提供 fields

例如,如果您想要检索创建的电子表格 title 及其 id,您可以改为执行以下操作:

creation_response = sheets_service.spreadsheets().create(body=spreadsheet, fields="spreadsheetId,properties.title").execute()

更新:

根据你对 Tanaike I want to add three separate tabs to the Google Sheet called abc, def, and ghi from the value set. 的评论,我终于明白了你想要的目标。在这种情况下,您应该以不同的方式构建有效负载。

考虑到 col1 是电子表格中工作表标题的集合,您可以这样做:

col1 = {"abc", "def", "ghi"}
SHEETS_DATA = list(map(lambda sheetName: {
    "properties": {
        "title": sheetName
    }
}, col1))
spreadsheet = {
  "properties": {
    "title": "YOUR_SPREADSHEET_TITLE"
  },
  "sheets": SHEETS_DATA 
}
creation_response = sheets_service.spreadsheets().create(body=spreadsheet).execute()

注:

发出请求后,使用 get(val) 将导致错误,因为 abc 不是响应中的字段(您应该从资源电子表格中指定一个字段,因为那是响应将是)。

参考: