4

I am trying to use the Google sheet API via python. So far I have been successful in performing some tasks. My problem is for example I have 4 sheets in a particular worksheet in the order of

[sheet1][sheet2][sheet3][sheet4]. 

What I want is to manipulate the positions of the sheets. For example, sheet 4 would now be located at the second position. So now, the positions of the sheets would become

[sheet1][sheet4][sheet2][sheet3]

Is there a way to do this in python?

Thanks!

wescpy
  • 10,689
  • 3
  • 54
  • 53
overmind
  • 467
  • 1
  • 8
  • 17
  • I show an example of moving sheets around, including properly setting the `fields` parameter, in the Google Apps Script language [here](https://stackoverflow.com/a/54206167/9337071). Note that the GAS client library syntax is very similar to that needed for the Python client library. – tehhowch Mar 13 '19 at 13:29

2 Answers2

2

It should be definitely doable, because Google Sheets API supports this and the Google API Python Client is just a wrapper around this and other APIs.

See the Sheets API reference for SheetProperties, the property is called index.

Try to implement this and come back if you need any help.

petr
  • 1,099
  • 1
  • 10
  • 23
2

Yes, you can do this in Python or any other language supported by the Google APIs Client Libraries. Regardless of which language, you need to use the latest Google Sheets API. Let's say you don't know where sheet4 is but want to move it to the 2nd slot as you've diagrammed.

Here are your steps, assuming SHEETS is your service endpoint, and FILE_ID is the ID of the Sheets file in your Google Drive:

  1. Find the ID of the sheet you want to move by getting your Sheets file data: rsp = SHEETS.spreadsheets().get()
  2. Cycle through each sheet, i.e., for sheet in rsp['sheets'] and match sheet['properties']['title'] == 'sheet4'
  3. Now update the properties of that sheet by setting its index to 2 with something like the request below.

Here's the code for the last part:

reqs = {'requests': [
    # reorder sheet4 to index 2
    {'updateSheetProperties': {
        'properties': {
            'sheetId': sheet['properties']['sheetId'],
            'index': 2
        }
    }}
]}
SHEETS.spreadsheets().batchUpdate(
    spreadsheetId=FILE_ID, body=reqs).execute()

Sheets 2 & 3 should slide over after you've made this change. Hope this helps!

If you've already played around with the samples in the docs and want to learn more by seeing some "real-world" examples of using the Sheets API with Python, I've made a couple of videos that may be useful:

wescpy
  • 10,689
  • 3
  • 54
  • 53