How do I iterate through Google sheet data and list in Google Doc?

I'm trying to take data from spreadsheet cells and list them in a google doc. I've tried with a forEach method, and a "for" loop. With the "for" loop when I Logger.log() the array it shows as expected, listing all the array items. When I try to write these items to a Google Doc the way every piece of instruction I can find indicates I should write it, it returns an empty document. I've tried various ways of getting the desired output within the "for" loop, as seen commented out below.

Help would be greatly appreciated.

function myFunction() {
    let ss = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = ss.getActiveSheet();
    let lastRow = sheet.getLastRow();
    let lastColumn = sheet.getLastColumn();
    let sheetData = sheet.getSheetValues(1, 1, lastRow, lastColumn);
    let description = sheet.getSheetValues(6, 3, 15, 1);

    //Creates document and places in folder
    let placementFolder = DriveApp.getFolderById('ID')
    let newDoc = DocumentApp.create('Placeholder')
    let docID = newDoc.getId()
    let body = newDoc.getBody()

    let open = DriveApp.getFileById(docID).moveTo(placementFolder)

    //Destination folder
    let destFolder = DriveApp.getFileById('ID')

    //DriveApp.getFileById(docID).moveTo(destFolder)

    for (i = 0; i < description.length; i++) {
        //let descArray = description[i].values() //Returns Empty Doc
        //let desc = newDoc.getBody().setText(description[i]) // Returns Empty Doc
        //body.editAsText().setText(description[i]) //Returns Empty Doc
        //DocumentApp.openById(docID).getBody().setText(description[i]) //Returns Empty Doc
        //body.appendParagraph(i) // Lists numbers 1-14 in Doc



        Logger.log(description[i]) // Returns list of items in array as expected
    }
}

1 answer

  • answered 2021-06-26 09:03 Yuri Khristich

    As far as I can understand your goal you need to put this line inside your loop:

    body.appendParagraph(description[i][0]);
    

    If you don't like the loop you can replace it with forEach() this way:

    description.forEach(x => body.appendParagraph(x[0]));
    

    It will do the same thing.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum