如何使用应用脚本从Google文档中删除文本?

时间:2020-05-06 15:15:34

标签: google-apps-script google-docs

我最近刚刚使用Google Script和Form / Sheets构建了一系列文档。

该文档使用初始表单中提供的数据通过脚本在Google文档中生成。

设置基本上如下:

要通过的条件

  • 班级:{{CLASS}}
  • 最低成绩:{{MINIMUM_GRADE}} / 10
  • 最低出勤率:{{ATTENDANCE_PERC}}%,整个学期至少有{{ATTENDANCE}}出勤率

将表单输入放在{{}}之间。

当前,这种情况下将显示类似以下内容:

  • 班级:三年级
  • 最低等级:不适用/ 10
  • 最低出勤率:70%,整个学期至少15出勤率

但是我想要:

  • 班级:三年级
  • 最低出勤率:70%,整个学期至少有15出勤率

如果此问题的答案为“不适用”,有什么办法可以使Google脚本自动删除任何要点,例如“最低成绩”?

1 个答案:

答案 0 :(得分:0)

答案:

您可以获取文档的所有子项,如果Element对象是LIST_ITEM ,则可以从主体中删除该子项。 em> Element对象包含文本“不适用”。

更多信息:

文档的结构非常棘手,但是知道给定的子代是LIST_ITEM元素类型,您可以检查它是否包含所需的文本,然后从子代的正文中删除该子代。文档。

代码:

function removeListItem() {
  var body = DocumentApp.getActiveDocument().getBody();
  var noOfChildren = body.getNumChildren();
  var childrenToRemove = [];
  
  for (var i = 0; i < noOfChildren; i++) {
    var child = body.getChild(i);
    var childType = child.getType();
    if (childType == DocumentApp.ElementType.LIST_ITEM) {
      if (child.asListItem().findText("Not Applicable") !== null ) {
        childrenToRemove.push(child); 
      }
    }
  }
  
  childrenToRemove.forEach(function(child) {
    try {
      body.removeChild(child);
    }
    catch(e) {
      Logger.log(e)
      if (e == "Exception: Can't remove the last paragraph in a document section.") {
        body.appendPageBreak()
        body.removeChild(child);
      }
    }
  });
}

我希望这对您有帮助!

参考文献:

相关问题