Search code examples
pythongoogle-sheets-apigspread

python / gspread - How to update a range of cells with a data list?


I have a data list (extracted from CSV) and I'm trying to use Python / GSpread to update a range of cells on a Google Doc. Here is my code sample:

import gspread
def write_spreadsheet(spreadsheet_name, sheet_id, data, start_row):
    gc = gspread.login('yourmail@gmail.com', 'password')
    wks = gc.open(spreadsheet_name).get_worksheet(sheet_index)
    start_letter = 'A'
    end_letter = string.uppercase[len(data[0]) - 1]
    end_row = start_row + len(data) - 1
    range = "%s%d:%s%d" % (start_letter, start_row, end_letter, end_row)

    print "Range is: " + range
    cell_list = wks.range(range)

    try:
        for i, val in enumerate(data):  #gives us a tuple of an index and value
            cell_list[i].value = val    #use the index on cell_list and the val from cell_values

        #Update the whole sheet
        wks.update_cells(cell_list)

    except:
        print "Exception"

this_data_ex = [['data1', 'data1'], ['data2', 'data2']]
write_spreadsheet('python-test', 1, this_data_ex, 1)

This works, but it does not separate the list row entries into the correct columns. Output on Google sheets looks like this:

    A                  B

['data1', 'data1'] ['data2', 'data2']

How can I fix the "try - for" section to write each data entry to a new cell, then wrap the row at the correct place? (like this)

 A   |  B

data1 | data1

data2 | data2


Solution

  • A Double nested for loop; one for the rows, one for the columns, then update each cell individually. This section seemed to work properly with the desired outcome:

     try:
        idx = 0
        for (start_row, rowlist) in enumerate(data):
            for (colnum, value) in enumerate(rowlist):
                cell_list[idx].value = value
                idx += 1
                if idx >= len(cell_list):
                    break
    
        # Update the whole sheet
        wks.update_cells(cell_list)