Search code examples
pythongoogle-sheets-apigspread

Getting gspread to update multiple spreadsheet files with the same data


As above I'm trying to update more than one sheet file with the same information using the sheet IDs as the identifier. I''ve attempted to achieve this with for loops with no success. Some of the basic code that I'm trying to achieve this with is:

conn = gspread.authorize(credentials)
sheets = ['sheetid1', 'sheetid2']
worksheet_list = conn.open_by_key(sheets).worksheet("Rack Layout")
worksheet_list.update_acell('Q1', 'some cell value')

So if I define 'sheets' as one sheetid the updates work fine, however if I define 'sheets' as more than one sheet I get the error. I know this is really basic and I think the issue is its trying to open the full list (i.e. both sheetids) on the same line, rather than saying 'run this line for one sheetID and then the next'. I think the way to achieve this is a for loop, but I've yet to get this to work with a for loop. I know this is a nube question, but I've been trying for a while now, and from my searching I haven't found any other forum posts about getting gspread to do this.


Solution

    • You have 2 Google Spreadsheets.
      • 2 Google Spreadsheets have the sheet of "Rack Layout", respectively.
    • You want to put the value of "some cell value" to the cell "Q1" in the sheet of "Rack Layout" for each Spreadsheet.
    • You want to achieve this using gspread with python.
    • You have already been able to get and put values for Spreadsheet using Sheets API.

    If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

    In this modified script, the value is put to each Spreadsheet using the for loop.

    Modified script:

    conn = gspread.authorize(credentials)
    sheets = ['sheetid1', 'sheetid2']
    for sheet in sheets:  # Added
        worksheet_list = conn.open_by_key(sheet).worksheet("Rack Layout")
        worksheet_list.update_acell('Q1', 'some cell value')
    

    If I misunderstood your question and this was not the direction you want, I apologize.