T
T
transcend2021-03-03 17:37:25
Google Apps Script
transcend, 2021-03-03 17:37:25

How to access multiple Google Spreadsheets via AppsScript?

I have a document in Google Spreadsheets with multiple sheets. On each of the sheets there is a table with data. Let's call them List1, List2

To get data in JSON, I use the following code through the Apps Script script editor:

var ss = SpreadsheetApp.getActiveSpreadsheet(), // spreadsheet
      s = ss.getActiveSheet(); // sheet

function getData(){
  var result = [],
      range = 'A:F', // диапазон ячеек, который хотим выгружать
      values = s.getRange(range).getValues(),
      last_row = parseInt(s.getLastRow());
    
  for (var i = 1; i < last_row; i++) {
      result.push(values[i]);     
  }
  return result; 
}


function doGet() {
  var data = getData();
  if(!data) {
    data = '';
  }
  return ContentService.createTextOutput(
    JSON.stringify({'result': data})).setMimeType(ContentService.MimeType.JSON);
}


I deploy the script and get a link that gives JSON.

The question is, how to make it so that you can access the desired sheet of choice? Those. if needed to List1, if needed to List2?

In AppsScript, if you make a copy of the file and change the code to:
var ss = SpreadsheetApp.getActiveSpreadsheet(), // spreadsheet
      s = ss.getSheetByName("List2"); // sheet

function getData(){
  var result = [],
      range = 'A:F', // диапазон ячеек, который хотим выгружать
      values = s.getRange(range).getValues(),
      last_row = parseInt(s.getLastRow());
    
  for (var i = 1; i < last_row; i++) {
      result.push(values[i]);     
  }
  return result; 
}


function doGet() {
  var data = getData();
  if(!data) {
    data = '';
  }
  return ContentService.createTextOutput(
    JSON.stringify({'result': data})).setMimeType(ContentService.MimeType.JSON);
}


then we get access again to only one sheet and the deployed script will give data only from it.

Need a solution to access any sheet.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor L, 2021-03-10
@transcend

And if you just accept get with a parameter, pass a sheet in the parameter?

function doGet(e){
  var list = e.parameter.list;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question