简体   繁体   中英

Creating New Tabs via Python in Google Sheets using Google API

I need to create a tab for each value in a set via Python. I've successfully made a connection to Google Sheets using Google API and have been able to update it. I've been unable to figure out how to iterate through creating each tab for each unique value in the set. My problem is that I want to to name each tab dynamically with the unique value and it's been causing an error.

Unique values set example: col1 = {abc,def,ghi}

Sample Code:

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)   

Error:

  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'."}]}]">

Issue:

You are not providing a valid value at fields .

Explanation:

fields is an optional request parameter that can be used to set which information from the spreadsheet you want to be returned. Therefore, the values you can set to fields are very limited.

abc is not an existing field in Spreadsheet , and that is causing the request to be invalid.

Solution:

You can do one of the following, depending on what you want to do:

  • If you want to return specific fields, specify one or several (comma-separated) fields that exist in the spreadsheet resource (with nested fields being dot-separated or inside parentheses).
  • Set fields to * to return all fields.
  • Don't provide fields if you want to return all default response fields for this resource.

For example, if you want to retrieve the created spreadsheet title and its id , you would do the following instead:

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

Update:

Based on your comment to Tanaike I want to add three separate tabs to the Google Sheet called abc, def, and ghi from the value set. , I could finally understand your desired goal. In this case, you should build the payload in a different way.

Considering that col1 is a set with the titles of the sheets in your spreadsheet, you could do something like this:

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()

Note:

After making the request, using get(val) will result in an error, since abc is not a field in the response (you should specify a field from the resource spreadsheet instead, since that's what the response will be).

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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