Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix the error http 400 "unable to parse range"?

I'm trying to connect python to Google Sheet. I followed the python quick start page : https://developers.google.com/sheets/api/quickstart/python .

I want to write to my google sheet with python but got an error

the error i got was

https://sheets.googleapis.com/v4/spreadsheets/1VToTIofV5MNKJa-9nZ0J1r6CmRqynV361_xYHCxdsSA/values/Sheet%201%21A4%3AZ?valueInputOption=RAW&alt=json returned "Unable to parse range: Sheet 1!A4:Z">

and this is a new and blank sheet

here are my codes

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 datetime
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
BOOKING_SPREADSHEET_ID = '1VToTIofV5MNKJa-9nZ0J1r6CmRqynV361_xYHCxdsSA'
def get_service():
    """
    """
    creds = None
    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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('sheets', 'v4', credentials=creds)
    return service
def write_values():
    service = get_service()

    values = [
        [
            'Yes', 'No', 'Yes'
        ],
        [
            'Yes', 'No', 'Yes'
        ]
    ]
    body = {
        'values': values
    }

    # sheet_name = '15/4/2019'
    sheet_name = 'Sheet 1'
    range_values = sheet_name + '!A4:Z'

    result = service.spreadsheets().values().update(
        spreadsheetId=BOOKING_SPREADSHEET_ID, range=range_values,
        valueInputOption='RAW', body=body).execute()
    print('{0} cells updated.'.format(result.get('updatedCells')))
if __name__ == '__main__':
     write_values()
    ##test()

and here is the link for my doc

like image 415
macklabsc Avatar asked Oct 15 '25 03:10

macklabsc


1 Answers

Had the same issue. Solved it by changing this

 sheet_name = 'Sheet 1'
    range_values = sheet_name + '!A4:Z'

to

range_values = "'Sheet 1'!A4:Z"

Hope this helps anyone with this issue

like image 84
italomero Avatar answered Oct 16 '25 15:10

italomero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!