6

I'm trying to change column width with Google Sheets API. I know that spreadsheetId I can get with ss_drive.get('id') but I don't know how to get sheetId:

ss_drive = drive_api.files().create(body=file_metadata).execute()
ssId = ss_drive.get('id')

sheets_api = build('sheets', 'v4', credentials=credentials)

requests = []
requests.append({
    "updateDimensionProperties": {
    "range": {
      "sheetId": sheetId,
      "dimension": "COLUMNS",
      "startIndex": 0,
      "endIndex": 1
    },
    "properties": {
      "pixelSize": 160
    },
    "fields": "pixelSize"
    }
})

response = sheets_api.spreadsheets().batchUpdate(
    spreadsheetId=ssId, body={'requests': requests}).execute()

I changed "sheetId": sheetId to "sheetId": 0. And the column changed its width.

F. Vosnim
  • 476
  • 2
  • 8
  • 23

1 Answers1

1

You can have multiple sheets stored in your account, so you need to know the sheet ID beforehand. You can log in to https://sheets.google.com, navigate to the sheet of your choice and the URL will look something like:

https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms

The token after the d/ is the spreadsheet's ID which you can use in your queries according to the developer example.

a_guest
  • 34,165
  • 12
  • 64
  • 118
  • I can get `1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms` from your example using this command: `ss_drive.get('id')`. It is called `spreadsheetId`. My question is how can I get `"sheetId": sheetId`? They are not the same. – F. Vosnim Mar 16 '20 at 20:34
  • @F.Vosnim It depends on how you named that sheet. If you don't know what's there you can get an overview with `spreadsheets().get`. See the question I linked. – a_guest Mar 16 '20 at 20:45
  • I mean all you said doesn't help to change the column width. I placed `"sheetId": 0` in my code and it changed the width of the column successfully. This means that `Sheet1, Sheet2, Sheet3...` have `sheetId= 0, 1, 2...`. Consider your example `1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms ` is your `spreadsheetId`, but the first sheet inside this spreadsheet has `sheetId=0`. – F. Vosnim Mar 16 '20 at 21:02
  • 1
    @F.Vosnim As long as you don't delete sheets that's true. Now delete `Sheet1` and the first sheet still has `sheetId == 1`. So in general you can't assume that the id of the first sheet is `0`. The same applies if you move sheets around. – a_guest Mar 16 '20 at 21:08
  • You right, I deleted the first sheet and the second sheet became `'sheetId': 876005509` – F. Vosnim Mar 16 '20 at 21:16