How to find a row based on an ID and then edit the row with gspread python

I want to find a row based on an ID then, and edit the whole row. The way I am trying (Which might not be the most optimal way), is by finding the row using .find() but even tho I can find the content of the row I can't fint the Range to Edit:

sheet = client.open(Sheets.sheetname).worksheet(worksheet)
row = sheet.row_values(sheet.find(str,in_column=1).row)
return row

This will return: [{'id': 3, 'date': '2020/12/26', 'country': 'chile', 'city': 'Torres del Paine', 'name': 'Punta Arenas/Torres del Paine', 'comment': 'Viagem de Onibus', 'address': 'Puerto Natales Chile', 'latitude': -51.7308935, 'longitude': -72.4977407, 'cost': '$0.00', 'days': 1, 'category': 'bus', 'media': 'www.youtube.com'}]

But I can't find the range of this row to perform an .update()

Any ideas? Thanks!

Upvotes: 1

Views: 1454

Answers (1)

Nikko J.
Nikko J.

Reputation: 5543

You can get the range by manipulating the row and col properties of find() method.

Try this code below:

import gspread

#convert number to column letter    
def colnum_string(n):
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

gc = gspread.service_account()
sh = gc.open("test").sheet1
cell = sh.find("3",in_column=1)

#get row number
row = cell.row
#get column number
col = cell.col

col_start = colnum_string(col)
row_len = len(sh.row_values(row))
col_end = colnum_string(row_len)
print("range is: %s%s:%s%s" % (col_start, row, col_end, row))

Output:

range is: A4:D4

Sheet1:

Sheet1

References

finding a cell

convert number to spreadsheet letter

Upvotes: 2

Related Questions