Michael Krezalek
Michael Krezalek

Reputation: 114

Create google sheet using Google Sheet API in shared drive

I want to create a sheet in a shared drive. I can create a sheet using the code below; however, it is in my drive, and I cannot find a way to edit properties to create where I want.

     service = build('sheets', 'v4', credentials=creds)

     sheet = service.spreadsheets()
     
     spreadsheet = {
         'properties': {
             'title': "title"
         }
     }
     
     request = service.spreadsheets().create(body=spreadsheet)
     response = request.execute()

     print(response)

Upvotes: 2

Views: 1337

Answers (1)

Tanaike
Tanaike

Reputation: 201378

I believe your goal is as follows.

  • You want to create a new Google Spreadsheet for the shared Drive.
  • From your showing script, you want to achieve this using googleapis for python.

Modification points:

  • In the current stage, when your creds is from your account, a new Google Spreadsheet cannot be directly created to the shared Drive using Sheets API. In this case, it is required to use Drive API. In order to achieve your goal, there are 2 patterns.

Pattern 1:

In this pattern, Sheets API and Drive API are used.

folderId = "###" # Please set the folder ID of the shared drive you expect.

# Create a new Spreadsheet.
service = build("sheets", "v4", credentials=creds)
spreadsheet = {"properties": {"title": "sample"}}
request = service.spreadsheets().create(body=spreadsheet)
response = request.execute()
print(response)
spreadsheetId = response["spreadsheetId"]

# Move Spreadsheet to your Google Drive to shared Drive.
drive = build("drive", "v3", credentials=creds)
res = drive.files().update(fileId=spreadsheetId, body={}, addParents=folderId, removeParents="root", supportsAllDrives=True).execute()
print(res)

Pattern 2:

In this pattern, only Drive API is used. When Drive API is used, a new Spreadsheet can be created in the shared Drive by one API call.

folderId = "###" # Please set the folder ID of the shared drive you expect.

drive = build("drive", "v3", credentials=creds)
body = {
    "name": "sample",
    "parents": [folderId],
    "mimeType": "application/vnd.google-apps.spreadsheet",
}
res = drive.files().create(body=body, supportsAllDrives=True).execute()
print(res)

Note:

  • If you want to put the new Spreadsheet in the root folder in the shared Drive, please use the drive ID to folderId.

References:

Upvotes: 4

Related Questions