繁体   English   中英

使用 Apps 脚本将表格从电子表格附加到 Google 文档

[英]Appending tables to Google Docs from Spreadsheets using Apps Script

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

由于.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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM