Home > OS >  Sorting the sheets in a google sheets worksheet
Sorting the sheets in a google sheets worksheet

Time:10-23

I am reading data from google sheets, writing data to google sheets, and want to rearrange the sheets inside the worksheet:

CLIENT_SECRET_GOOGLE_SHEETS = r"client_secret_google_sheets.json"
creds = ServiceAccountCredentials.from_json_keyfile_name(CLIENT_SECRET_GOOGLE_SHEETS, GSHEETS_SCOPES)
client = gspread.authorize(creds)
sheet = client.open("my_worksheet")

worksheet_list = sheet.worksheets()
# worksheet_list 

[<Worksheet 'Documentation' id:35>,
 <Worksheet 'week 2' id:15>,
 <Worksheet 'week 1' id:20>]

I would like to change it to:

[<Worksheet 'Documentation' id:35>,
 <Worksheet 'week 1' id:20>,
 <Worksheet 'week 2' id:15>]

I tried searching for this functionality but was not able to find it in gspread documentation.

UPDATE

After using Tanaike's answer the order is not consistent:

[<Worksheet 'Documentation' id:35>,
 <Worksheet 'week 1' id:20>,
 <Worksheet 'week 10' id:150>,
 <Worksheet 'week 11' id:16>,
 <Worksheet 'week 2' id:115>,]

CodePudding user response:

I believe your goal is as follows.

  • You want to realign the sheets in a Google Spreadsheet.
  • You don't want to include the 1st worksheet. You want to sort other sheets except for 1st tab by the sheet name.
  • You want to achieve this using gspread for python.

In this case, how about the following sample script?

Sample script:

In this modification, the sheets except for the 1st tab are sorted by the batchUpdate method.

client = ### # Please use your client in your script.
spreadsheetId = "###" # Please set the Spreadsheet ID.

# 1. Retrieve all sheets.
spreadsheet = client.open_by_key(spreadsheetId)
sheets = spreadsheet.worksheets()
sheets.pop(0)

# 2. Sort sheets except for 1st tab.
sortedSheets = sorted(sheets, key=lambda x: x.title)

# 3. Create request body.
requests = []
for i, sheet in enumerate(sortedSheets):
    requests.append({
        "updateSheetProperties": {
            "properties": {
                "index": i   1,
                "sheetId": sheet.id
            },
            "fields": "index"
        }
    })

# 4. Request to Sheets API.
res = spreadsheet.batch_update({"requests": requests})

References:

  • Related