How to set each column with different size in Google Sheet with python API v.4?

Question:

I have a spreadsheet on my google drive created by python api.

I need to set the individual size of each column in the sheet.

I wonder, is there any way to do this with one Request call? Or the only way is to go to each column on loop cycle an set each one individually? What if I have, for example, the list of sizes for each column? Can I set these sizes by one Request?

I’ve searched the api documentation, but still can’t find the solution.

Thanks

Asked By: Ivan Lebedev

||

Answers:

About I need to set the individual size of each column in the sheet. and I wonder, is there any way to do this with one Request call?, I think that it’s yes. I think that your goal can be achieved by the batchUpdate method of Sheets API. The sample script is as follows.

Sample script:

In this sample, googleapis for python is used.

service = ###  # Please use your script.

spreadsheet_id = "###"  # Please put your Spreadsheet ID.
sheet_id = "0"  # Please put the sheet ID of the sheet you want to use.

# Please set your expected column numbers and column width.
# In this sample, the column width of columns "A" and "C" are set as 200 and 300 pixels, respectively.
column_widths = [
    {"columnNumber": 1, "width": 200},
    {"columnNumber": 3, "width": 300},
]

requests = [
    {
        "updateDimensionProperties": {
            "properties": {"pixelSize": e["width"]},
            "range": {
                "dimension": "COLUMNS",
                "sheetId": sheet_id,
                "startIndex": e["columnNumber"] - 1,
                "endIndex": e["columnNumber"],
            },
            "fields": "pixelSize",
        }
    }
    for e in column_widths
]
service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body={"requests": requests}).execute()
  • When this script is run, the column width of columns "A" and "C" of sheet_id are set as 200 and 300 pixels, respectively.
  • In this script, this process can be achieved by one API call.

References:

Answered By: Tanaike