简体   繁体   中英

Looking for one Google Script App for 4 sheet tabs to produce one json

Ok...not sure how to do this. Right now I 4 sheets and 4 scripts for each sheet producing 4 json feeds. What I am trying to experiment with is having one script that will produce 1 json that I can use in a web page and just call the type of class. They are all formatted the same with columns etc.

Here is the Google Script App code I have.

    function doGet(e){

 // Change Spread Sheet url
 var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/SpreadsheetID/edit#gid=0");

// Sheet Name, Change Sheet to whatever name you used to name your sheet
 var sheet = ss.getSheetByName("Class Sheet 1");

 return getClasses(sheet); 

}

function getClasses(sheet){
  var dataObj = {};
  var dataArray = [];

// collecting data starting from 2nd Row , 1st column to last row and last column
  var rows = sheet.getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn()).sort([{column: 1, ascending: true}, 1]).getValues();

  for(var i = 0, l= rows.length; i<l ; i++){
    var dataRow = rows[i];
    var record = {};

    record['Name'] = dataRow[0];
    record['Note'] = dataRow[1];
    record['Address'] = dataRow[2];
    record['StreetAddress'] = dataRow[3];
    record['City'] = dataRow[4];
    record['State'] = dataRow[5];
    record['ZipCode'] = dataRow[6];
    record['ContactName'] = dataRow[7];
    record['EMailAddress'] = dataRow[8];
    record['CustomerServicePhone'] = dataRow[9];

    dataArray.push(record);

  }

  dataObj = dataArray;

  var result = JSON.stringify(dataObj);

  return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);

 } 

Scratching my head on this a little bit....I'm sure its something simple and I am probably over thinking things, but any help would be appreciated.

Possible Solution:

The e object in your doGet(e) provides a way to send parameters to your script. You can access different sheets with different url parameters. You can then easily get the requested SheetName through e.parameter . Use

https://script.google.com/.../exec?sheet=ClassSheet1 //for ClassSheet1
https://script.google.com/.../exec?sheet=ClassSheet2 //for ClassSheet2

Code.gs:

function doGet(e){
 var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/SpreadsheetID/edit#gid=0");
 var sheetName = e.parameter.sheet;
 var sheet = ss.getSheetByName(sheetName);
 return getClasses(sheet); 
}

You can also provide UI in your web-app to select a sheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM