首页 > 解决方案 > 用表格替换搜索文本

问题描述

希望我能在这方面得到一些建议。我正在使用脚本来自动创建文档,其中数据来自现有的谷歌文档。在使用链接表没有运气之后,我试图在文档中由搜索文本标识的点插入一个表。

例如,我会在文档中搜索 TABLE1HERE 并将其替换为由[[Heading,Data],[Heading2,MoreData]]. 我已经尝试了以下代码和许多变体,但都没有运气。任何指针都会很棒。

function updateTablesTEST(searchText,replacementTable){

  var document = DocumentApp.getActiveDocument();
  var documentBody = document.getBody();
  var textLocation;
  var newPosition;
  var textChild;

  textLocation = documentBody.findText(searchText).getElement();
  textChild = textLocation.getParent().getChildIndex(textLocation);
  documentBody.insertTable(textChild+1, replacementTable);

}

标签: google-apps-scriptgoogle-sheetsgoogle-docs

解决方案


用表格替换文本

这将找到包含所需文本的容器的 childIndex。它删除文本并将表格插入到同一个子项中。

function searchTextReplTable(texttofind){
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var rgel=body.findText(texttofind);
  var element=rgel.getElement();
  var childIndex=body.getChildIndex(element.getParent());
  var t=[];//This is the table I used
  for(var i=0;i<5;i++){//just created a 5,5 table with row, col indices
    t[i]=[];
    for(var j=0;j<5;j++){
      t[i][j]=Utilities.formatString('%s,%s',i,j);
    }
  }
  body.getChild(childIndex).asText().setText('');
  body.insertTable(childIndex,t)
}

推荐阅读