Search code examples
pythongoogle-sheetsgspread

Formatting using Row & Column coordinates in GSpread python


I couldn't find any resources on how to format the google spreadsheet in gspread python using the row and column values instead of A1 notations.

I have a spreadsheet with 50 rows and I don't want to find the notation of the 50th column. Rather I like to use the row and column coordinates like (1,50) -> first row with 50 columns to make them bold and adjusting the width of all the columns.

Please suggest and thanks in advance


Solution

  • I'm able to format the cells using row and column coordinates using the below function. Accumulated different answers available for the related questions in Stackoverflow. Thank you.

    def formatHeaderRow(gs, ws):
    
        #to change the column width of the specific range of cells using row and column numbers
        sheetId = ws._properties['sheetId']
        numOfColumns = 26 # Keep your column number here
        body = {
            "requests": [
                {
                    "updateDimensionProperties": {
                        "range": {
                            "sheetId": sheetId,
                            "dimension": "COLUMNS",
                            "startIndex": 0, #from A1
                            "endIndex": numOfColumns # 26 -> A26
                        },
                        "properties": {
                            "pixelSize": "150"
                        },
                        "fields": "pixelSize"
                    }
                }
            ]
        }
        res = gs.batch_update(body)
        
        #to bold the first row using row number
        ws.format("1", {
            "textFormat": {
                "bold": True
                }
        })