简体   繁体   中英

Google Sheets API in Python, Creating a Spreadsheet then editing, Spreadsheet isn't found

This is my code, which i basically copied from the text quickstart.py that google provides.

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os

SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
CLIENT_SECRET_FILE = 'creds.json'
copyFromE = 'sheetIdGoesHere'
copyFromId = 'spreadsheetIdGoesHere'


def createSheet():
    global service, spreadsheetId

    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secretfile.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    spreadsheet = {
        'properties': {
        'title': nameDoc,
        'locale': 'en_US',  # optional
        'autoRecalc': 'ON_CHANGE',
        # calculation setting #https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#RecalculationInterval
        'timeZone': 'CDT-05:00'},
    }
    spreadsheet = service.spreadsheets().create(body=spreadsheet,
                                                fields='spreadsheetId').execute()
    spreadsheetId = 'Spreadsheet ID: {0}'.format(spreadsheet.get('spreadsheetId'))
    print(spreadsheetId)

if __name__ == '__main__':
    createSheet()

This succesfully creates a Spreadsheet in Google Spreadsheets. I can see it from the drive homepage in my internet browser. The error happens after this, when I try to import a sheet from another Spreadsheet.

request = service.spreadsheets().sheets().copyTo(spreadsheetId=copyFromId, sheetId=copyFromE,
                                                  body={'destinationSpreadsheetId': spreadsheetId}).execute()

For some reason I get the error:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/ copyFrom /sheets/ copyFromE :copyTo?alt=json(Here is where the target Spreadsheet id should be)returned "Invalid destinationSpreadsheetId [Spreadsheet ID: spreadsheetId ]">

This is the weird part because the Spreadsheet has been created. I can see it from the drive homepage in my internet browser. If I insert the spreadsheetId in the browser, the URL works too. So the sheet exists and it is there. If I double click the created spreadsheet in my driver, after being created, it opens a blank spreadsheet with the name I have assigned in nameDocs with the exact same URL stored on the spreadsheetId variable. Basically, the Spreadsheet is there, stored in my account, it WAS created. The information is correct, but the program can't find it.

The next weird thing is this: if I run the script that imports a sheet from another Spreadsheet after opening the created Spreadsheet via browser, the script works.

I'm trying to automate reports from my job which I have to do manually, and will save me hours of work. I have tried opening the created spreadsheet via Selenium and then run the "copy sheet from spreadsheetId code (pasted above)" but for some reason Selenium does not open the URL, which the browser opens if I type the exact same thing manually, so that is out of the picture. Any ideas why this is happening? Or any ideas to come up with a solution to this problem?

Issue:

You are not retrieving the spreadsheet ID, but a string formatted like this:

Spreadsheet ID: {your-spreadsheet-id}

The API is trying to access a spreadsheet whose ID is this string. Logically, it's not finding it: take a look at the error you're getting:

Invalid destinationSpreadsheetId [Spreadsheet ID: spreadsheetId] .

The "Spreadsheet ID: " part should not be there.

Solution:

After creating the new spreadsheet, retrieve the spreadsheet ID like this:

spreadsheetId = spreadsheet.get('spreadsheetId')

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