Search code examples
pythongoogle-sheets-apigspread

gspread set column type/format


I'm using gpread to write data into google sheet. The data is written correctly, but I need to set a whole specific column to be of type "Number" so that it can be ordered by default without having to change the column format by hand each time. This column has only numbers (besides the header).

This is the code where I update the sheet and try to set the column type. The data is written correctly, but I haven't been able to correctly change the format for the column R (it treats them as strings, so it orders them like 101,50,9 instead of 9,50,101):

sheet.clear()

sheet.update([lol.columns.values.tolist()] + lol.values.tolist())
sheet.format("R", { "numberFormat": { "type": "NUMBER" }})

How can I change the column R format to Number?


Solution

  • Instead of this:

    sheet.format("R", { "numberFormat": { "type": "NUMBER" }})

    Try this:

    sheet.format("R", { "numberFormat": { "type": "NUMBER","pattern": "#,##0" }})

    What I recommend when you don't know how to format something using a client library is to get its current format using the Google API.

    E.g. You have a cell with the correct format of the numbers as you desire.

    Then using this API you fill it out as follows:

    spreadsheetId = Your spreadsheet ID
    ranges = Your Cell reference goes here
    fields = *
    

    Execute it and then the results you'll see:

          "data": [
            {
              "startRow": x,
              "startColumn": x,
              "rowData": [
                {
                  "values": [
                    {
                      "userEnteredValue": {
                        "numberValue": xxxxxxxxx
                      },
                      "effectiveValue": {
                        "numberValue": 950101
                      },
                      "formattedValue": "950,101",
                      "userEnteredFormat": {
                        "numberFormat": {
                          "type": "NUMBER",
                          "pattern": "#,##0"
                        }
    

    And this is what you'll use:

                        "numberFormat": {
                          "type": "NUMBER",
                          "pattern": "#,##0"
    

    - Number format tokens