Search code examples
pythongoogle-sheets-apipygsheets

How to write a list of URLs to a google drive spreadsheet with pygsheets


I have a list of urls that I'm trying to upload to a spreadsheet with pygsheets. For some reason, instead of updating cells in the specified range, the script only updates one cell. Relevant part of the script below:

wks = sheet.sheet1
wks.update_cells('A1:A5',[[img]])

where img is a list of URLs. Any help would be greatly appreciated!

updated snipped of code

res_list = []
wks = sheet.sheet1
header = wks.cell('A1')
header.value = 'URLs'
for i in res_list:
   wks.update_values(crange='A2:A1000',
   values=np.array([[image_name]]).tolist(), majordim='ROWS')

Solution

  • the update_cells take a matrix (list of lists). so remove the extra outer list. This should work.

    now as you are writing each value in each column, you should convert your values into column major form

    matrix = list(map(list, zip(*[img])))
    wks = sheet.sheet1
    wks.update_cells('A1:A5',[img])
    

    else change major dimension

    wks = sheet.sheet1
    wks.update_cells('A1:A5',[img], majordim="COLUMNS")
    

    EDIT: updated code

    res_list = []
    wks = sheet.sheet1
    header = wks.cell('A1')
    header.value = 'URLs'
    j=2
    for i in res_list:
       image_name = get_new_name() # get the new url/value for next cell
       wks.update_values(crange="A"+str(j), values=np.array([[image_name]]).tolist())
       j+=1
    

    EDIT2: working version (switched to earlier version of pygsheets)

        res_list = []
        wks = sheet.sheet1
        h = res_list
        im_name = [str(i) for i in h]
        for i in im_name:
            wks.update_cell('A'+str(im_name.index(i)+1), i)