Home > Back-end >  Access to sheets by name while adressing the fg.sheet file by URL
Access to sheets by name while adressing the fg.sheet file by URL

Time:11-26

I'm in a situation where I need to send data to specific tabs(sheet) in a google sheet file (basically it's a G.Sheet file with one sheet that is a "template"). two cases: a/ the needed sheet exists then just append the data in that one, if not then use a specific sheet (template) copy it to create the new sheet as a new tab and append in it the data sent. Each new sheet get its name as a parameter in the flow of data to be appended. I'm really confused and know where to start and hope I'm clear enough. So far I have this little code (not including the copying of the template cuz I don't know how to do it).

// pseudo is the name of the sheet in the file

function doGet(e) { 
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/IDXXX/edit#gid=0");
  var sheet = ss.getSheetByName(e.pseudo); 
  
  addData(e,sheet);
}
 
function doPost(e) { 
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/IDXXX/edit#gid=0");
  var sheet = ss.getSheetByName(e.pseudo); 
  
  addData(e,sheet);
}
 
 
function addData(e,sheet) {
  //some data to append in the e.pseudo sheet
var id = e.parameter.id ;
var date = e.parameter.date ;
var textRef = e.parameter.textRef ;
var niveau = e.parameter.niveau ;
var cycle = e.parameter.cycle ;
var vitesse = e.parameter.vitesse ;
var reference = e.parameter.reference ;
sheet.appendRow([id,date,textRef,niveau,cycle,vitesse,reference]);

}

CodePudding user response:

I would have thought e.psuedo should have been e.parameter.psuedo

CodePudding user response:

You can refer to this sample code on how to create a new sheet from a template sheet. Assuming your sheet name can be obtained in e.pseudo or in e.parameter.psuedo as what @Cooper advised.

// pseudo is the name of the sheet in the file

function doGet(e) { 
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/IDXXX/edit#gid=0");
  var sheet = ss.getSheetByName(e.pseudo); 
  
  // Sheet doesn't exit, create new sheet from a template
  if (sheet == null) {
    // Select "template" sheet and copy to the current Spreadsheet
    sheet = ss.getSheetByName("template").copyTo(ss);
    // Rename the copied template sheet
    sheet.setName(e.pseudo);
  }
  
  addData(e,sheet);
}

What it does?

Note:

  • just replace the name of your template sheet
  • Related