首页 > 解决方案 > 如何从谷歌文档中获取字数到谷歌表格上

问题描述

我有一个包含一堆谷歌文档的文件夹,我需要制作一个电子表格来自动跟踪每个文档的字数。有没有办法只用公式来做到这一点?深入研究 google docs API 是唯一的选择吗?如果是这样,有什么好的起点吗?

标签: google-sheetsgoogle-sheets-apigoogle-docs

解决方案


我很确定如果没有 Google App Scripts,就不可能将文档正文拉入 google 表格。您可能会尝试使用导入功能或其他东西来确保,但我认为您仍然必须让文件对整个互联网公开可见。

您也不能使用谷歌表格功能进行驱动器呼叫。但是,您可以运行可能为您提供所需内容的宏。在下面的代码中,我编写了一个宏,该宏从单元格 A2 开始并转到文档末尾以查找httpdocument. 如果它们存在,它会执行字数统计并最终插入到 URL 的右侧。

这是我运行的示例:

在此处输入图像描述

这是代码:

function populateSheetWithWordCountValuesMacro(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var theRange = ss.getRange(2,1,ss.getLastRow(),1)
  var theValues = theRange.getValues();
  var theCount = [];

  for(var i=0;i<theValues.length;i++){
    var theResult = theValues[i][0];
    if(theResult.slice(0,4)=="http"){
      theCount.push([countWordsInDocument_(theResult)]);
    }else{
      theCount.push([null]);
    }
  }
   theRange.offset(0,1).setValues(theCount);
}


function countWordsInDocument_(theDocumentURL){
  const theRegex = new RegExp("[A-Za-z]") // or include other ranges for other languages or numbers
  var theDoc = DocumentApp.openByUrl(theDocumentURL);
  var theText = theDoc.getBody().getText();

  var wordStarted = false;
  var theCount = 0;
  for(var i=0;i<theText.length;i++){
    var theLetter = theText.slice(i,i+1);
    if(theRegex.test(theLetter)){
      if(!wordStarted){
        wordStarted=true;
        theCount++;
      }
    }else if(wordStarted){
      wordStarted=false;
    }
  }
  return theCount;
}

推荐阅读