【问题标题】:Find if a Google Document is blank using google script使用谷歌脚本查找谷歌文档是否为空白
【发布时间】:2017-05-16 10:38:02
【问题描述】:

如何使用 App 脚本查找 google 文档是否为空白?我试过这个

function myFunction() 
{
  var body = DocumentApp.getActiveDocument().getBody();
  var para = body.getParagraphs();
  var count = 0;
  for (i = 0; i < para.length; i++) 
  {
    if (para[i].getText() != "")
     count++;  
  }
  if(count=0)
   Logger.log("Empty");
  else
   Logger.log("NOT EMPTY")
}

我确信这只有在文档只有文本内容时才有效。我很想知道是否有任何方法可以找到文档是否为空白。

【问题讨论】:

    标签: google-apps-script google-docs google-drive-realtime-api


    【解决方案1】:

    一个文档总是至少有一个段落元素,所以你不能真正依赖零计数返回。您可以检查正文中元素的长度,然后触发更多测试以真正检查空白。

    function blankDoc() {
      var body = DocumentApp.getActiveDocument().getBody();
    
      // Find the number of children in the body
      Logger.log(body.getNumChildren());
    
      for(var i = 0; i<body.getNumChildren();i++) {
        Logger.log(body.getChild(i).getType());
    
        // Test for text in the paragraph
        if(body.getChild(i).getType() == DocumentApp.ElementType.PARAGRAPH) {
    
          // get the text, check for a 0 length
          var para = body.getChild(i).asParagraph().getText();
          Logger.log(para.length);
          // use another if block to do something...
        }
      }
      // check for images
      var imgs = body.getImages();
    
      if(imgs.length > 0) {
        Logger.log("There's an image");
      }
    }
    

    它并不完美,但它让你更接近。通过documentation 了解要在文档的Body 中检查哪些元素,然后从那里添加。

    【讨论】:

    • 感谢您的想法,尝试了这个function blankDoc() { var body = DocumentApp.getActiveDocument().getBody(); var blankDoc; var child = body.getNumChildren(); var para = body.getChild(0).asParagraph().getText(); if(child==1 &amp;&amp; para.length == 0) { blankDoc = true; } else { blankDoc = false; } return blankDoc; },它成功了@brian
    • 太棒了。如果你想关闭它,你可以点击左边的绿色复选标记。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多