I want to create an empty Google Sheet (created only with metadata) in Google Drive. When I referred to the Google SpreadSheet API documentation, it says to use the DocumentsList API, but it's deprecated and instead asks me to use the Google Drive API. In the Drive API docs, I could not find any way to create an empty Sheet. Anyone have a clue on how to do this?
You can do this using the Drive API by setting the MIME type to application/vnd.google-apps.spreadsheet
:
To do this in Python:
from apiclient.discovery import build
service = build('drive', 'v2')
import httplib2
credentials = ... # Obtain OAuth 2.0 credentials
http = credentials.authorize(httplib2.Http())
body = {
'mimeType': 'application/vnd.google-apps.spreadsheet',
'title': 'Name of Spreadsheet',
}
file = service.files().insert(body=body).execute(http=http)
# or for version 3 it would be
# file = service.files().create(body=body).execute(http=http)
Head over to the Google APIs Explorer to try it out!
(Jul 2016) BossyLobster's answer above is still valid (as Drive API v2 has not been deprecated [yet]). However, below are more modern ways of doing the same thing and some videos to help with understanding:
Authorization boilerplate for both examples below
from googleapiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
NOTE: to create your API project and OAuth2 credentials as well as download those credentials to the client_secret.json
(or client_id.json
) file, go to the Google Developers Console.
Create new/blank Sheet w/Google Drive API v3 (& v2)
# above: SCOPES = 'https://www.googleapis.com/auth/drive.file'
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
data = {
'name': 'My new Sheet',
'mimeType': 'application/vnd.google-apps.spreadsheet',
}
sheet = DRIVE.files().create(body=data).execute() # insert() for v2
Create new/blank Sheet w/Google Sheets API v4
# above: SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
SHEETS = discovery.build('sheets', 'v4', http=creds.authorize(Http()))
data = {'properties': {'title': 'My new Sheet'}}
sheet = SHEETS.spreadsheets().create(body=data).execute()
Now you may ask, "Why are there two different ways of creating a blank Sheet?" To put it succinctly, the Sheets API is meant primarily for spreadsheet-oriented operations, i.e., inserting data, reading spreadsheet rows, cell formatting, creating charts, adding pivot tables, etc., not file-oriented requests like create/delete and import/export, where the Drive API is the correct one to use. It just so happens that create is sort-of both, hence why there are two ways of doing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With