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

风流意气都作罢 提交于 2019-12-07 19:31:46

问题


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!


回答1:


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.




回答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:

  • Migrating SQL data to a Sheet (code deep dive post)
  • Formatting text using the Sheets API (code deep dive post)
  • Generating slides from spreadsheet data (code deep dive post)


来源:https://stackoverflow.com/questions/42004124/move-a-sheet-to-a-particular-position-using-python-the-google-sheets-api

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