【问题标题】:How do I iterate through Google sheet data and list in Google Doc?如何遍历 Google 表格数据并在 Google Doc 中列出?
【发布时间】:2021-06-26 01:39:15
【问题描述】:

我正在尝试从电子表格单元格中获取数据并将它们列在谷歌文档中。我尝试过使用 forEach 方法和“for”循环。当我 Logger.log() 使用“for”循环时,它会按预期显示数组,列出所有数组项。当我尝试将这些项目写入谷歌文档时,我能找到的每条指令都表明我应该写它,它返回一个空文档。我已经尝试了各种在“for”循环中获得所需输出的方法,如下所示。

我们将不胜感激。

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
    }
}

【问题讨论】:

    标签: javascript google-apps-script google-docs google-workspace


    【解决方案1】:

    据我所知,您需要将此行放入循环中:

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

    如果你不喜欢这个循环,你可以用forEach()这样替换它:

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

    它会做同样的事情。

    【讨论】:

    • 非常感谢!!这行得通。我已经阅读了我能得到的所有内容,并重新访问了 Code Academy 部分,但仍然不明白为什么每个选项都需要 [0]。看来我需要再复习一下基础知识。
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    相关资源
    最近更新 更多