How do I format a header row in Google Sheets API v4 in C#?

Viewed 3208

I want the following output:

But I receive the following result:

I followed the instructions on this SO question:

How to Change color of range in google sheets api v4 in .net

But this code is bold on all rows and columns of the sheet.

How can I solve this problem? My Code is:

var userEnteredFormat = new CellFormat()
{
    TextFormat = new TextFormat()
    {
        Bold = true,
        FontSize = 12
    }
};

BatchUpdateSpreadsheetRequest batchupdateCell = new BatchUpdateSpreadsheetRequest();

//create the update request for cells from the first row
var updateCellsRequest = new Request()
{
    RepeatCell = new RepeatCellRequest()
    {
        Range = new GridRange()
        {
            SheetId = sheetId,
            StartColumnIndex = 0,
            StartRowIndex = 0,
            EndColumnIndex = 28,
            EndRowIndex = 1
        },
        Cell = new CellData()
        {
            UserEnteredFormat = userEnteredFormat
        },
        Fields = "UserEnteredFormat(TextFormat)"
    }
};

batchupdateCell.Requests = new List<Request>();
batchupdateCell.Requests.Add(updateCellsRequest);
SpreadsheetsResource.BatchUpdateRequest bur = service.Spreadsheets.BatchUpdate(batchupdateCell, SheetId);
BatchUpdateSpreadsheetResponse responseUpdate3 = bur.Execute();
1 Answers

This works just fine for me using the Google APIs Explorer, which should translate almost 1:1 between the JSON POST body and the C#/Python/Java/... typed resource.

POST https://sheets.googleapis.com/v4/spreadsheets/YOUR_SPREADSHEET_ID_HERE:batchUpdate?
     fields=updatedSpreadsheet(sheets(data%2FrowData%2Fvalues%2FuserEnteredFormat%2Cproperties(sheetId%2Ctitle)))
{
    "requests": [
        {
            "repeatCell": {
                "range": {
                    "sheetId": YOUR_SHEET_ID_HERE,
                    "endRowIndex": 1
                },
                "fields": "userEnteredFormat/textFormat",
                "cell": {
                    "userEnteredFormat": {
                        "textFormat": {
                            "bold": true,
                            "fontSize": 12
                        }
                    }
                }
            }
        }
    ],
    "responseRanges": [
        "1:2"
    ],
    "includeSpreadsheetInResponse": true
}

Demo link

The GridRange in my request identifies only the sheetId and the ending index, so it targets all columns in the given sheet, and formats only the first row. (an end index of 2 would format the 1st and 2nd rows unless the start index was given as 1, per the API spec).

For verification purposes, the demo link is configured to request that the Sheets API sends you back the TextFormat of the first 2 rows on every sheet, along with the title and sheetId SheetProperties. Note that if no user format was applied to the second row, no data will be sent for it.

Related