在 Google Apps 脚本中添加新的 Table 行(1 行 2 列)

Append a New Table Row (1 Row 2 Columns) on Google Apps Script

我正在尝试制作一个自动化脚本,根据来自 Google 表单的用户响应更新现有的 Google 文档。所以有 3 个问题(姓名、大学编号标识或马来语中的 NIM,以及部门或 bidang),用于对每个受访者进行分类的部门问题。

因此,目标是每当提交表单时,文档也会更新。因此,我想让更新生成一个新行,其中包含一个包含模板字符串的单元格,我已经在电子表格的脚本中使用了该模板字符串。但问题是它只为每一行附加一列,然而,这不是我想要发生的。我希望它更新 1 行和 2 列。

Screenshot Of the Google Form

Screenshot of the Google Docs Error

Screenshot of what I intended the Google Docs when it's updated to be

function appendTable(variabel){
      var rangePSDI = body.findText(variabel);
      var searchElement = body.findElement(DocumentApp.ElementType.TABLE, rangePSDI);
      element = searchElement.getElement();
      table = element.asTable();
      table.appendTableRow().appendTableCell(variabel);
  }

  if (bidang == 'PSDI') {
      body.replaceText('{{NamaPSDI}}', nama);
      body.replaceText('{{NIMPSDI}}', nim);
      appendTable("{{NamaPSDI}}");
      appendTable("{{NIMPSDI}}");
      return;
  } else if (bidang == 'PSDM') {
      body.replaceText('{{NamaPSDM}}', nama);
      body.replaceText('{{NIMPSDM}}', nim);
      appendTable("{{NamaPSDM}}");
      appendTable("{{NIMPSDM}}");
      return;
  }

想想appendTableRow as <tr> in HTML where you have to set the cell using <td>or appendTableCell

参见 HTML 中的 Table Row element

试试这个:

代码:

function appendTable(){
  var doc = DocumentApp.openById('someid');
  var body = doc.getBody();
  var tables = body.getTables();
  var text = "PSDM";
  tables.forEach(table => {
    if(table.getCell(0,0).getText() == text){
      table.replaceText("{{Nama"+text+"}}", "test nama"+text)
      table.replaceText("{{NIM"+text+"}}", "test NIM"+text)
      var tr = table.appendTableRow();
      tr.appendTableCell("{{Nama"+text+"}}");
      tr.appendTableCell("{{NIM"+text+"}}");
    }
  })
}

之前:

之后:

PSDI

PSDM