Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to autofit a column in Google Sheets using gspread API for Python?

Is there a way to manipulate row with in Google Sheets using gspread API for Pyton? Autofit will be great but manually change size is ok too.

like image 758
Georgi Bonchev Avatar asked Sep 01 '25 03:09

Georgi Bonchev


1 Answers

  • You want to adjust the column width as "autofit" using Sheets API.
  • You want to achieve this using gspread.
  • You have already been able to put and get values for Spreadsheet using gspread.

If my understanding is correct, how about this sample script? Please think of this as just one of several answers.

In this sample script, I used "autoResizeDimensions" with batch_update() of gspread. This uses spreadsheets.batchUpdate of Sheets API.

Sample script:

spreadsheetName = "###"  # Please set Spreadsheet name.
sheetName = "###"  # Please set sheet name.

ss = client.open(spreadsheetName)
sheetId = ss.worksheet(sheetName)._properties['sheetId']
body = {
    "requests": [
        {
            "autoResizeDimensions": {
                "dimensions": {
                    "sheetId": sheetId,
                    "dimension": "COLUMNS",
                    "startIndex": 0,  # Please set the column index.
                    "endIndex": 2  # Please set the column index.
                }
            }
        }
    ]
}
res = ss.batch_update(body)

Note:

  • In the above sample script, startIndex and endIndex uses 0 and 2, respectively. This means that the width of column "A" and "B" of sheetName are automatically resized.
  • If you want to use Spreadsheet ID, please modify ss = client.open(spreadsheetName) to ss = client.open_by_key(spreadsheetId).

References:

  • batch_update(body)
  • Method: spreadsheets.batchUpdate
  • AutoResizeDimensionsRequest

If I misunderstood your question and this was not the direction you want, I apologize.

like image 189
Tanaike Avatar answered Sep 02 '25 16:09

Tanaike