Search code examples
pythongoogle-sheetsgoogle-sheets-apigoogle-api-client

Python sort google sheets API by column


I researched the topic and found this: Google Sheets API Sort column by date The problem is that it sorts by column A.

So I changed it to the following:

    request = {
            "requests": [
                {
                    "sortRange": {
                        "range": {
                            "sheetId": sheet_id,
                            "startRowIndex": 1,
                            "startColumnIndex": 0
                        },
                        "sortSpecs": [
                            {
                                "dataSourceColumnReference": {
                                    "name": "D"
                                },
                                "sortOrder": "DESCENDING"
                            }
                        ]
                    }
                }
            ]
        }
    sheets_service.batchUpdate(body=request, spreadsheetId=spreadsheet_id).execute()

But it still sort it by column A.


Solution

  • In your showing request body, the columns are sorted by the 1st column. If you want to sort the columns by another column instead of the 1st column, please use the property of dimensionIndex. The default of this value is 0. By this, the 1st column is used when dimensionIndex is not used.

    For example, if you want to sort the columns by the 3rd column (column "C"), please use dimensionIndex: 2 as follows.

    request = {
      "requests": [
        {
          "sortRange": {
            "range": {
              "sheetId": 0,
              "startRowIndex": 1,
              "startColumnIndex": 0
            },
            "sortSpecs": [
              {
                "dataSourceColumnReference": {
                  "name": "D"
                },
                "sortOrder": "DESCENDING",
                "dimensionIndex": 2 # <--- here
              }
            ]
          }
        }
      ]
    }
    sheets_service.batchUpdate(body=request, spreadsheetId=spreadsheet_id).execute()
    
    • The 1st value of dimensionIndex is 0.

    References: