Move a sheet to a particular position using Python & the Google Sheets API

坚强是说给别人听的谎言 提交于 2019-12-06 09:56:46

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.

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!