4

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.

Georgi Bonchev
  • 269
  • 4
  • 12

1 Answers1

11
  • 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:

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

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • Thank you! That was very usefull. I guess in this way I can change all other properties as color, font size etc. – Georgi Bonchev Aug 05 '19 at 05:34
  • 1
    @Georgi Bonchev Thank you for replying. I'm glad your issue was resolved. Yes. You can also modify other properties using `batch_update()`. – Tanaike Aug 05 '19 at 07:32
  • 1
    @Tanaike This was very helpful. Good idea to state your understanding, it helps incoming browsers understand what your answer is for! – Jérémie Mar 25 '20 at 02:21