【问题标题】:Appending tables to Google Docs from Spreadsheets using Apps Script使用 Apps 脚本将表格从电子表格附加到 Google 文档
【发布时间】:2021-01-04 21:15:46
【问题描述】:

我一直在学习使用 Google Apps 脚本。我必须为我的作业做的一项任务是通过从 Google 电子表格中获取数据将表格附加到 Docs。我设法简单地复制了一个数据范围并从中创建了一个表,但现在我需要使用一些条件,例如只复制那些包含特定值的行。我在哪里可以找到这个问题的可能解决方案?在这里或互联网上的其他地方找不到类似的东西......

【问题讨论】:

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


    【解决方案1】:

    由于.getValues()的返回值是二维数组,所以可以使用JavaScript的Array.filter()方法。

    例子:

    在我的工作表中,我想过滤所有打篮球的人。

    表格:

    应用脚本:

    function myFunction() {
      //retrieve data from Sheet
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
      var range = sheet.getDataRange().getValues();
    
      var filteredData = range.filter(function(item){
        //return if the 3rd column("Sports") is equal to "Basketball"
        return item[2] == "Basketball";
      });
      //filteredData : [[John, 11.0, Basketball], [Robin, 9.0, Basketball]]
    
      //Append the header data (Name, Age, Sports) to the beginning of the array
      filteredData.unshift(range[0])
    
      //filteredData : [[Name, Age, Sports], [John, 11.0, Basketball], [Robin, 9.0, Basketball]]
    
      //Create document
      var doc = DocumentApp.create('Example');
      var body = doc.getBody();
      //Create table to Docs and use the filteredData as values.
      var table = body.appendTable(filteredData);
      //Set the header to bold.
      table.getRow(0).editAsText().setBold(true);
    }
    

    文档:

    参考资料:

    Array.filter()

    【讨论】:

    • 非常感谢,这正是我所需要的。另外,我想问一下如何选择要附加到表格的列?例如,如果我只想将第 1 列和第 3 列附加到 Docs
    • 如果您有兴趣,我有一个工具可以在适当的降价中创建表格。您可以观看视频并从here 获取代码。用markdown 编写的表格的优点之一是可以复制数据。
    猜你喜欢
    • 2015-06-25
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2020-04-29
    相关资源
    最近更新 更多