Search code examples
pythongoogle-sheetsgoogle-sheets-apigspread

How to create multiple sheets in a spreadsheet by gspread and python?


I am new to Python and wanna practice using gspread and python to deal with spreadsheets. Now I already knew how to connect google spreadsheet with gspread, but still cannot figure out how to create multiple sheets at once.

My expectation:

  1. Create multiple sheets naming by Employees' names at once
  2. So every employee can use their own sheet

Thanks in advance!

employee_name = ['Jonny','Emma', ...]


Solution

  • You can do this, for example:

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    
    # Set up the credentials and client
    scopes = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scopes)
    client = gspread.authorize(credentials)
    
    # Open the spreadsheet
    spreadsheet = client.open("My Spreadsheet")
    
    # Get the list of employee names
    employee_names = ['Jonny', 'Emma', ...]
    
    # Iterate over the list of names and create a sheet for each of the employee
    for name in employee_names:
      spreadsheet.add_worksheet(title=name, rows=100, cols=20)
    

    This is going to open the sheet, get the list of employees and loop over the list and in that way, you create a new sheet for each employee with the name of the actual employee as the sheet title. Hope it helps

    References: https://docs.gspread.org/en/v5.7.0/