Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/gspread - how can I update multiple cells with DIFFERENT VALUES at once?

To update a range of cells, you use the following command.

## Select a range
cell_list = worksheet.range('A1:A7')

for cell in cell_list:
    cell.value = 'O_o'

## Update in batch
worksheet.update_cells(cell_list)

For my application, I would like it to update an entire range, but I am trying to set a different value for each individual cell. The problem with this example is that every cell ends up with the same value. Updating each cell individually is inefficient and takes way too long. How can I do this efficiently?

like image 477
ecollis6 Avatar asked May 21 '13 16:05

ecollis6


People also ask

What is Gspread in Python?

gspread is a Python API for Google Sheets. Features: Google Sheets API v4. Open a spreadsheet by title, key or url. Read, write, and format cell ranges.


2 Answers

You can use enumerate on a separate list containing the different values you want in the cells and use the index part of the tuple to match to the appropriate cells in cell_list.

cell_list = worksheet.range('A1:A7')
cell_values = [1,2,3,4,5,6,7]

for i, val in enumerate(cell_values):  #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

worksheet.update_cells(cell_list)
like image 102
ecline6 Avatar answered Oct 05 '22 10:10

ecline6


  1. Import modules
import gspread
from gspread.cell import Cell
from oauth2client.service_account import ServiceAccountCredentials
import string as string
import random
  1. Create cell array with values
cells = []
cells.append(Cell(row=1, col=1, value='Row-1 -- Col-1'))
cells.append(Cell(row=1, col=2, value='Row-1 -- Col-2'))
cells.append(Cell(row=9, col=20, value='Row-9 -- Col-20'))
  1. Find the sheet
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('Sheet-Update-Secret.json', scope)
client = gspread.authorize(creds)
  1. Update the cells
sheet.update_cells(cells)

You could refer to my blog post for more details.

like image 37
Prince Francis Avatar answered Oct 05 '22 09:10

Prince Francis