Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

google apps script - Writing an element on each row of a new sheet

I have a data array. I would like to write each element of the array onto a row in a new sheet. In addition, I would like each element within an element to be in the next cell along. I'm not sure about how I go about doing this.

I think that a nested for loop might be solution which is what I have tried below. It manages to print each element onto the Logger; now I just need a way to write it to a spreadsheet in rows.

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var data = [['Mr. Gerald', 'Monday', '2:10'], ['Mr. Holmes', 'Tuesday', '3:00']]
  var dataSheet = ss.getActiveSheet()
  var startRange = dataSheet.getRange(1,1)

  for (var i = 0; i < data.length;i++) {
    for (var a = 0; a<data[i].length; a++) {
      Logger.log(data[i][a])
    }}  
}

The output should look like this

Any help will be appreciated, thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your data is in the actual format that's required in the sheet:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var data = [['Mr. Gerald', 'Monday', '2:10'], 
              ['Mr. Holmes', 'Tuesday', '3:00']];
  var dataSheet = ss.getActiveSheet();
  dataSheet.getRange(1,1,data.length,data[0].length).setValues(data); //or use Advanced Google Services    
}

If data is not of square/rectangular shape, Use Advanced Google services:

  var request = {
    range: dataSheet.getName() + '!A1',
    majorDimension: 'ROWS',
    values: data,
  };
  //API must be enabled before use. 
  //https://developers.google.com/apps-script/advanced/sheets
  Sheets.Spreadsheets.Values.update(request, ss.getId(), request.range, {
    valueInputOption: 'USER_ENTERED',
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...