繁体   English   中英

使用 Google App 脚本复制文档标题

[英]Copy Document Title Using Google App Script

我想从本文档的标题中复制文本,但我只习惯在工作表中使用 Google App Script,而不是文档: 文本在文档中的位置

我尝试了很多不同的方法,但 Logger.log() 中没有填充任何内容,所以我不确定它是否有效。 目前,我只想返回标题中的文本,因此我可以拨打 go 在电子表格中搜索它。 到目前为止,我有以下内容:

function autoFill() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var searchResult = body.findElement(DocumentApp.ElementType.PARAGRAPH);
  var searchHeading = searchResult.getElement(DocumentApp.ParagraphHeading.TITLE);

文档中唯一具有标题格式的部分是文档中的第一行。

下面是如何查找标题样式为标题的段落的示例。 在我的文档中,我有一行带有标题样式的文本“这是一些文本”。

function findTitle() {
  try {
    let doc = DocumentApp.getActiveDocument();
    let body = doc.getBody();
    let paras = body.getParagraphs();
    let text = null;
    paras.some( para => {
        let attribs = para.getAttributes();
        if( attribs["HEADING"] === DocumentApp.ParagraphHeading.TITLE ) {
          text = para.getText();
          return true;
        }
        return false;
      }
    );
    console.log(text);
  }
  catch(err) {
    console.log(err);
  }
}

执行日志

8:08:39 AM  Notice  Execution started
8:08:39 AM  Info    This is some text
8:08:39 AM  Notice  Execution completed

发现使用Regular Expression就能识别出需要的文字:

 function autoFill() {
  var ss = DocumentApp.getActiveDocument();
  var body = ss.getBody();
  var header = DocumentApp.getActiveDocument().getHeader();
  var contents = body.getText();
  var racm = SpreadsheetApp.openById('[enter sheet ID').getSheetByName('Risks & Controls matrix');
  var lr = racm.getLastRow();
  var colID = racm.getRange(1,1,lr,1).getValues();

//you need to tweak below to the control name pattern

  var regexName = /\w+[-]\w+[-]\w+/   //use website: regexr.com to create & www.geeksforgeeks.org/write-regular-expressions/
  var titleFound=regexName.exec(contents)[0];

let row = colID.findIndex(users => {return users[0] == titleFound})+1; 

然后继续在文档中的电子表格和.replaceText() 范围内查找相关数据。

效果很好。 谢谢你的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM