Search code examples
pythonpython-2.7colorsgoogle-sheets-apigspread

GSpread CellFormat foregroundColor


I am trying to colour my header in Google Sheets purple, however GSpread textFormat doesn't seem to bring back the correct colour.

I have looked through the GSpread documentation, and there is little on what format the colour code should be, so I just assumed RGB as thats what it looks like it should be.

Also looked through the Google Sheets API and that uses RGB.

fmt = CellFormat(textFormat=textFormat(bold=True, foregroundColor=color(112, 48, 160), fontSize=24),)
format_cell_range(worksheet, 'B1:B1', fmt)

The header should be the same colour as the following RGB code: (112, 48, 160)

Instead of this: (144, 208, 96)


Solution

    • You want to set the foreground color of a cell of Google Spreadsheet using gspread.
      • You want to set the cell "B1" to the color of 112, 48, 160 which is RGB.
    • You want to achieve this using gspread-formatting.
    • You have already been able to put and get values to the Spreadsheet using gspread.

    If my understanding is correct, how about this answer?

    Prepare:

    Before you use this modified script, please install gspread-formatting as follows. If you have already installed it, please skip this section.

    $ pip install gspread-formatting
    

    Modified script:

    Please set spreadsheetId and sheetName.

    import gspread_formatting as gsf  # <--- Also please add this to your script.
    
    spreadsheetId = "###"
    sheetName = "Sheet1"
    
    client = gspread.authorize(credentials)
    ss = client.open_by_key(spreadsheetId)
    worksheet = ss.worksheet(sheetName)
    fmt = gsf.cellFormat(
        textFormat=gsf.textFormat(
            bold=True, foregroundColor=gsf.color(112, 48, 160), fontSize=24)
    )
    gsf.format_cell_range(worksheet, 'B1:B1', fmt)
    

    References:

    If this was not useful for your situation, I apologize.