无法从Google Document中清除页脚

时间:2018-09-11 09:34:04

标签: google-apps-script google-docs

当我运行下面的代码时,我收到TypeError:

  

TypeError:无法调用null的方法“ clear”。 (第3行,文件“代码”)

从以下行:footer.clear()

function insertFooterDate() {
  var footer = DocumentApp.getActiveDocument().getFooter();
  footer.clear();  // Line 3 - gets the footer & clears all data in footer. 

  //Get date
  var date = new Date();
  var month = date.getMonth()+1;
  var day = date.getDate();
  var year = date.getFullYear();
  var hour = date.getHours()+1;
  var minute = date.getMinutes()+1;
  var filename = doc.getName();

  footer.appendParagraph(day + '/' + month + '/' + year + ' ' + filename);  
  //adds date to footer with filename
}

为什么我的代码执行时出现此错误?

1 个答案:

答案 0 :(得分:1)

如果Google Docs文件中没有页脚,则无法在不存在的页脚上调用方法。 Apps脚本文档服务提供了一种add a footer的方法,因此您应该决定中止需要页脚的方法(如果还没有页脚的话),或者创建一个方法。该决定将取决于您的方法应该执行的操作。

function doStuffWithFooter_(myGDoc) {
  if (!myGDoc) return;
  const footer = myGDoc.getFooter();
  if (!footer) {
    console.warn("Document '" + myGDoc.getId() + "' had no footer.");
    return;
  }
  ... // code that should only run if the doc already had a footer
}

function addDateToFooter_(myGDoc) {
  if (!myGDoc) return;
  var footer = myGDoc.getFooter();
  if (!footer) {
    // no footer, so create one.
    footer = myGDoc.addFooter();
    console.log("Created footer for document '" + myGDoc.getId() + "'.");
  }
  ... // do stuff with footer, because we made sure one exists.
}