简体   繁体   English

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

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

I have been learning to use Google Apps Scripts.我一直在学习使用 Google Apps 脚本。 One of the tasks which I have to do for my assignment is appending tables to Docs by taking data from Google Spreadsheets.我必须为我的作业做的一项任务是通过从 Google 电子表格中获取数据将表格附加到 Docs。 I managed to simply copy a data range and create a table from it, but now I need to use some conditions, for example copy only those rows that contain a specific value.我设法简单地复制了一个数据范围并从中创建了一个表,但现在我需要使用一些条件,例如只复制那些包含特定值的行。 Where could I search for possible solutions of this problem?我在哪里可以找到这个问题的可能解决方案? Can't find anything similar on here or elsewhere on the internet...在这里或互联网上的其他地方找不到类似的东西......

Since the return of .getValues() is two-dimensional array of values, you can use JavaScript's Array.filter() method.由于.getValues()的返回值是二维数组,因此可以使用 JavaScript 的 Array.filter() 方法。

Example:例子:

In my sheet, I want to filter all person playing Basketball.在我的工作表中,我想过滤所有打篮球的人。

Sheets:床单:

床单

Apps Script:应用脚本:

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

Docs:文件:

文档

References:参考:

Array.filter() Array.filter()

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

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