如何使用 Google 表格中的数据将数组插入到 Google 文档中?

How do I insert an array into a Google Doc using data from Google Sheets?

我正在尝试从 Google sheet 中提取一系列名称并将其放入 Google Doc.In 传播 sheet,姓氏 ("lastNames") 位于名字 ("firstNames") 之前,并且两者位于不同的列中。我正在尝试将名字和姓氏放在我的文档中,名字在前。

我使用 for 循环将名字和姓氏放在一个数组中(“fullNames”),这部分工作正常。当我使用 Logger.log 时,所有的名字和姓氏都在一个数组中,每个全名由一个公共名称分隔,就像我希望的那样。

我不知道该怎么做实际上是将这个新数组插入到文档正文中。我正在使用 appendTable 方法,但每次尝试时都会出现以下错误:“参数 (number[]) 与 DocumentApp.Body.appendTable 的方法签名不匹配。”

我必须对我的代码进行哪些更改才能将我的新数组实际放入我的 google 文档中?

function namePusher() {

var ss = SpreadsheetApp.openById("1CHvnejDrrb9W5txeXVMXxBoVjLpvWSi40ehZkGZYjaY");
var lastNames = ss.getSheetByName("Campbell").getRange(2, 2, 18).getValues();
var firstNames = ss.getSheetByName("Campbell").getRange(2, 3, 18).getValues();
//Logger.log(firstNames);


var fullNames = [];

for(var i = 0; i < firstNames.length; i++){
  var nameConcat = firstNames[i] + " " + lastNames[i]
  fullNames.push(nameConcat);
}
//Logger.log(fullNames); 


var doc = DocumentApp.getActiveDocument().getBody(); 
doc.appendTable(fullNames);

  
}

修改点:

  • 我认为您的问题有两个原因。
    1. getValues() 检索到的值是二维数组。
    2. data of appendTable(data) 必须是二维数组。
      • 在您的脚本中,fullNames 是一维数组。这样就出现了这样的错误。
  • 在您的脚本中,使用 2 getValues() 检索 2 列的值。在这种情况下,成本会变得有点高。您可以使用 getValues().
  • 检索值

当这些点反映到你的脚本中,就变成了下面这样。

修改后的脚本:

function namePusher() {
  var ss = SpreadsheetApp.openById("1CHvnejDrrb9W5txeXVMXxBoVjLpvWSi40ehZkGZYjaY");
  var values = ss.getSheetByName("Campbell").getRange("B2:C19").getValues();  // Modified
  var fullNames = [];
  for(var i = 0; i < values.length; i++){  // Modified
    var nameConcat = [values[i][1] + " " + values[i][0]];  // Modified
    fullNames.push(nameConcat);
  }
  var doc = DocumentApp.getActiveDocument().getBody();
  doc.appendTable(fullNames);
}

参考文献:

修复代码的一种简单方法是替换

fullNames.push(nameConcat);

来自

fullNames.push([nameConcat]);

你的脚本的问题是 fullNames 是一个 字符串数组 但你应该传递 Array 字符串数组(或可能被强制转换为字符串的对象)。

基本演示

var data = [
  ['A','B','C'],
  [1, 'Apple','Red'],
  [2, 'Banana','Yellow']
];

function myFunction() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  body.appendTable(data);
}

所述,还有其他“改进机会”

  1. 减少对 Google Apps 脚本 类 和方法
  2. 的调用次数
  3. 使用更好的方法来管理数组和连接字符串。