Search code examples
javagoogle-sheetsbackground-colorgoogle-sheets-api

Change the Color of a Cell through Google Sheet API: Invalid requests


I want to set the background color of a cell (or group of cell) through Google Sheet API.

I wrote this request, it perfectly works when I write .setFields("*"), but I can't do that because this overrides all the previous requests I performed on that cell.

So I specify .setFields("backgroundColor") according to the field name as seen in this document. But I get an error:

"message" : "Invalid requests[1].repeatCell: Invalid field: background_color",

Please note that backgroundColor has become background_color.

I tried other strings such as color, backgroundcolor... but none works. I don't know how to do.

  Color XgoogleColor = new Color().setRed(1f).setGreen(0f).setBlue(0f); // Color.RED

    return new Request()
            .setRepeatCell(new RepeatCellRequest()
                    .setCell(new CellData()
                            .setUserEnteredFormat(new CellFormat()
                                    .setBackgroundColor(XgoogleColor)
                            )
                    )
                    .setRange(new GridRange()
                            .setSheetId(sheetId)
                            .setStartRowIndex(startRow)
                            .setEndRowIndex(endRow)
                            .setStartColumnIndex(startColumn)
                            .setEndColumnIndex(endColumn)
                    )
                    .setFields("backgroundColor")
            );

Solution

  • I believe your situation and goal as follows.

    • In your script, when .setFields("*") is used, the script works.
    • You want to update only backgroundColor.

    In this case, please modify as follows.

    From:

    .setFields("backgroundColor")
    

    To:

    .setFields("userEnteredFormat.backgroundColor")
    
    • By this, backgroundColor is updated.

    Reference: