How to get data from Google Sheet to use in deploy

2019-09-14 20:28发布

I am using Google App scripts and am having trouble finding an answer to this fairly simple task: how can I get the data from a Google Sheet in my code.gs and then use it in a published web app (for some visualization w/ D3)?

I would like to get all columns and rows from the spreadsheet, then use those in the data. Preferably they would be in JSON for ease of use, but I can't find the specifics on how to grab all (or any) of the data from a Sheet in my code.gs and then use it in the index.html.

So far I have something like this:

code.gs

function getData(){
 var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k");

 //get desired range

 return sheet;
}

index.html

In the <script> in index.html:

 google.script.run.getData();

But am otherwise at a loss. Thanks for any help.

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-14 20:59

Getting the data is fairly easy. However this has to be properly done on both server side and client side.

For code.gs you will need to return actual data, but currently return sheet just returns the sheet object. What you need to do instead is

var vals = sheet.getDataRange().getValues()

which now gets you a 2D array of your sheet values. Now keep in mind that sheet has to be a sheet object not a spreadhseet object. So if your spreadsheet has many sheets, make sure you get the correct one with something like

var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k").getSheets()[0]; 

or

var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k").getSheetByName('Sheet1');

Now, since you want to grab the data as a JSON, all you really have to do is

vals = JSON.stringify(vals)

and now you have a JSON string of values. However that is just half of it, because your index.html that you wrote will not make use of the data as it calls the server side function, but does not listen for a response. In order to do that, you will need to use a success handler as written here. Essentially you will have to call a function in index.html that will make use of the returned vals variable. So something like

google.script.run.withSuccessHandler(useData).getData();

function useData(data) {
   data = JSON.parse(data)
   //now you have a 2D array in your index.html and you can use it as you wish within these client side scripts
}
查看更多
登录 后发表回答