为什么 Google 应用程序脚本仅在脚本执行结束后才将分页符和数据插入 table?

Why does a Google apps script insert a page break and data into a table only after the script execution ends?

我是 运行 Google 文档中的 GAS,要用 G' Sheets 中的一组数据填写 table。
当数据长于第一页的内容时,我将在第一页末尾的段落中插入一个分页符 table。其余数据插入到第二页的第二个table。
一切正常,但行和分页符仅在脚本完成执行后才添加到文档中。这给我带来了一个问题,因为我想在执行期间将 .gdoc 转换为 .docx,并且行不会转换为 .docx,因为它们在脚本结束之前不在 .gdoc 中。

function fillSampling(fileID, data) {
  var doc = DocumentApp.openById(fileID);
  var body = doc.getBody();
  var cellStyle = {};
  cellStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
  cellStyle[DocumentApp.Attribute.FONT_SIZE] = 8;
  cellStyle[DocumentApp.Attribute.BOLD] = false;
  var boldStyle = {};
  boldStyle[DocumentApp.Attribute.BOLD] = true;
  var table = body.getTables()[1];
  var tableHeader = table.copy();
  var r = 0;

  while(data[r]) {
    if(r==10) {
      body.insertPageBreak(body.getNumChildren()-1);
      table = body.appendTable(tableHeader);
    }
    var tableRow = table.appendTableRow();
    var c = 0;
    while(data[r][c]) {
      var cell = tableRow.appendTableCell(data[r][c]).setPaddingBottom(0).setPaddingTop(0);
      cell.getChild(0).asParagraph().setAttributes(cellStyle);
      if(c==0) cell.setAttributes(boldStyle);
      c++;
    }
    r++;
  }
}

这是填写第一个和后面table的函数。然后调用此函数的另一个函数继续将文档从 .gdoc 转换为 .docx。
谁能解释为什么行、分页符和第二个 table 似乎被缓存并且只在执行结束后才添加到文档中?
任何帮助将不胜感激,谢谢。

根据您的情况,我认为将以下脚本放在 fillSampling 函数的最后一行可以解决您的问题。

doc.saveAndClose();

参考: