Search code examples
javascriptgoogle-apigoogle-drive-apigoogle-api-js-client

Create new spreadsheet via GDrive REST API in Javascript?


I want to create a new spreadsheet in Google Drive, using the V4 REST API in Javascript. I can write data to an existing one, since I have an id, like this, once oauthed:

var accessToken=gapi.auth.getToken().access_token;
var str="https://sheets.googleapis.com/v4/spreadsheets/"+id+"/values/Sheet1!A1:E50?valueInputOption=USER_ENTERED";
var xhr=new XMLHttpRequest();
xhr.open("PUT",str);                                                                
xhr.setRequestHeader('Authorization','Bearer '+ accessToken);
xhr.send(JSON.stringify(data));

But I don't know how to create one from scratch in Javascript.


Solution

  • I understood that you want to create new Spreadsheet. If my understanding is correct, how about this modification?

    Sample script :

    var data = {"properties": {"title": "### filename of new spreadsheet ###"}}; // Added
    var accessToken=gapi.auth.getToken().access_token;
    var str="https://sheets.googleapis.com/v4/spreadsheets"; // Modified
    var xhr=new XMLHttpRequest();
    xhr.open("POST",str); // Modified
    xhr.setRequestHeader('Authorization','Bearer '+ accessToken);
    xhr.send(JSON.stringify(data));
    

    Note :

    • If the error related to scopes occurs, please check the reference.
    • data in this sample is very simple. So please modify it for your environment.

    Reference :

    If I misunderstand your question, I'm sorry.