0

I'm writing a python script to send data from a csv file to a Google Spreadsheet. I'm have a clear understanding of the basics need for this project, however I'm totally lost regarding formatting/parsing data from a csv file to the google sheet (I'm still learning python !).

So here is the first part of my code :

def add_todo():

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = 'spreadsheetidhere'
    rangeName = 'A1:A'
    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()

I didn't write it myself and it's working perfectly.

Here is the second part of my code :

test = []
with open('data.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
            test.append(row)

It's also working properly, even though I don't really know how I should mix it with the first part of my code. I've done this:

test = []

def add_todo():
    with open('snap.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
                test.append(row)
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = '1UJGs-gJCIUDv5jg5-p0MPEqsokYu5k2MfJ8A5oBkpWs'
    rangeName = 'A1:A'

    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()

As you can guess my main concern is how I should proceed to pass the data from the test array to the spreadsheet values values = {'values':[['Hello Saturn',],]}

I wanted to do something like this : values = {'values':[test]} but obviously it doesn't work.

To sum up, here is my csv file :

data1,data2,data3,data4,...
value1x,value2x,value3x,value4x,...
value1y,value2y,value3y,value4y,...
value1z,value2z,value3z,value4z,...

And here is what I want in my spreadsheet :

data1   data2   data3   data4 //col name
value1x value2x value3x value4x //row1
value1y value2y value3y value4y //row2
etc...

I'm totally lost between array, list, json format.

1 Answer 1

1

You need to specify the range parameter and body in the main API call. If you look at the API documentation you'll see that the body needs to have the following form

values = [
    [
        # Cell values ...
    ],
    # Additional rows ...
]
body = {
  'values': values
}

That is, a dictionary with one element values that is a list of lists. Your test variable that contains the CSV data already appears to be a list of lists, so you're good to go. You don't need to worry about JSON here, since the API's Python interface automatically translates your Python dictionaries and lists to JSON. The range parameter is a bit trickier but based on the docs using the sheet's name will make it append the values to the end of that sheet. So, putting the above together, your code might look something like this (I have not tested it):

def add_todo():
    test = []  # test should be initialized in the function body
    with open('snap.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
                test.append(row)
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = '1UJGs-gJCIUDv5jg5-p0MPEqsokYu5k2MfJ8A5oBkpWs'

    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values': test}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=spreadsheetId,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.