0

I have created a script to retrieve data from REST API. I can view all the array data in logger. How do I add all those data into rows. This is my current function:

function myFunction() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mainSheet = ss.getSheetByName("test")
  mainSheet.getRange('A1:A3').clear();

  var apiKey = 'test';

  var URL_STRING = "test";

  var url = URL_STRING + "?ApiKey=" + apiKey;

  var response = UrlFetchApp.fetch(url);
  var json = response.getContentText();
  var data = JSON.parse(json);
  var arr = [];
  //Logger.log(data.output.o1);

  for (var i=0;i<data.output.o1.length;i++){
    x=(data.output.o1[i].company_name);
    arr.push(x);
    Logger.log(arr);
  } 
}

This is the sample output for arr:

enter image description here

This is my expected output:

output

1 Answer 1

1

I believe your goal as follows.

  • You want to put the values of arr from row 2 of the column "A" in the sheet "test".

In this case, how about the following modification?

From:

for (var i=0;i<data.output.o1.length;i++){
  x=(data.output.o1[i].company_name);
  arr.push(x);
  Logger.log(arr);
}

To:

for (var i = 0; i < data.output.o1.length; i++) {
  x = (data.output.o1[i].company_name);
  arr.push([x]); // Modified
  Logger.log(arr);
}
mainSheet.getRange(2, 1, arr.length).setValues(arr); // Added
  • If you want to append the values to the sheet, please modify mainSheet.getRange(2, 1, arr.length).setValues(arr); as follows.

      mainSheet.getRange(mainSheet.getLastRow() + 1, 1, arr.length).setValues(arr);
    

References:

Sign up to request clarification or add additional context in comments.

7 Comments

i got an error saying Error Exception: The number of rows in the data does not match the number of rows in the range. The data has 1 but the range has 2.
Btw i tried this method. It can work. for (var i=0;i<data.output.o1.length;i++){ x=(data.output.o1[i].company_name); Logger.log(x); mainSheet.appendRow([x]); }
How do i append this in specific row and column?
@Sriram Thank you for replying. I apologize for the inconvenience. In that case, can you provide the sample values of arr after your for loop? And also, can you add your current script for replicating your issue? By this, I would like to confirm your situation. I thought that the error message of The data has 1 but the range has 2. means that you might use the script getRange(2, 1, arr.length, 2) instead of getRange(2, 1, arr.length).
thanks for your reply. I have added the sample output for arr
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.