Search code examples
javascriptarraysgoogle-apps-scriptgoogle-sheetsgoogle-docs

How do I insert an array into a Google Doc using data from Google Sheets?


I am trying to pull a range of names from a Google sheet and place it into a Google Doc.In the spreadsheet, the last names("lastNames") come before the first names ("firstNames"), and both are in separate columns. I am trying to place the first and last names together into my doc with the first names first.

I used a for loop to put the first and last names together into an array ("fullNames"), and that part works just fine. When I used Logger.log, all the first names and last names are together in an array, with each full name separated by a common, just the way I wanted them to be.

What I can't figure out how to do is actually insert this new array into the body of the document. I am using the appendTable method, but every time I try to I get the following error: "The parameters (number[]) don't match the method signature for DocumentApp.Body.appendTable."

What changes do I have to make to my code to actually place my new array into my google doc?

function namePusher() {

var ss = SpreadsheetApp.openById("1CHvnejDrrb9W5txeXVMXxBoVjLpvWSi40ehZkGZYjaY");
var lastNames = ss.getSheetByName("Campbell").getRange(2, 2, 18).getValues();
var firstNames = ss.getSheetByName("Campbell").getRange(2, 3, 18).getValues();
//Logger.log(firstNames);


var fullNames = [];

for(var i = 0; i < firstNames.length; i++){
  var nameConcat = firstNames[i] + " " + lastNames[i]
  fullNames.push(nameConcat);
}
//Logger.log(fullNames); 


var doc = DocumentApp.getActiveDocument().getBody(); 
doc.appendTable(fullNames);

  
}


Solution

  • One simple way to fix your code is by replacing

    fullNames.push(nameConcat);
    

    by

    fullNames.push([nameConcat]);
    

    The problem with your script is that fullNames is an Array of strings but your should pass an Array of Arrays of strings (or objects that might be coerced to strings).

    Basic demo

    var data = [
      ['A','B','C'],
      [1, 'Apple','Red'],
      [2, 'Banana','Yellow']
    ];
    
    function myFunction() {
      const doc = DocumentApp.getActiveDocument();
      const body = doc.getBody();
      body.appendTable(data);
    }
    

    As mentioned on Tanaike's answer there are other "improvement opportunities"

    1. Reduce the number of calls to the Google Apps Script Classes and Methods
    2. Use better ways to manage Arrays and to concatenate strings.