问题
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:
- Find the ID of the sheet you want to move by getting your Sheets file data:
rsp = SHEETS.spreadsheets().get()
- Cycle through each sheet, i.e.,
for sheet in rsp['sheets']
and matchsheet['properties']['title'] == 'sheet4'
- 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