5

我的目标是用另一个文档的内容替换 Google Drive 文档中的一段文本。

我已经能够将文档插入到另一个文档中的某个位置,但是我无法确定要替换的文本的子索引。这是我到目前为止所拥有的:

function replace(docId, requirementsId) {

var body = DocumentApp.openById(docId).getActiveSection();
var searchResult = body.findText("<<requirementsBody>>");
var pos = searchResult.?? // Here I would need to determine the position of the searchResult, to use it in the insertParagraph function below

var otherBody = DocumentApp.openById(requirementsId).getActiveSection();
var totalElements = otherBody.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
var element = otherBody.getChild(j).copy();
  var type = element.getType();
  if( type == DocumentApp.ElementType.PARAGRAPH ) {
      body.insertParagraph(pos,element);   
  } else if( type == DocumentApp.ElementType.TABLE ) {
    body.insertTable(pos,element);
  } else if( type == DocumentApp.ElementType.LIST_ITEM ) {
    body.insertListItem(pos,element);
  } else {
    throw new Error("According to the doc this type couldn't appear in the body: "+type);
  }
}


};

任何帮助将不胜感激。

4

2 回答 2

6

findText()

返回一个 RangeElement。

您可以使用

var r = rangeElement.getElement()

获取包含找到的文本的元素。

要获取它的 childIndex,您可以使用

r.getParent().getChildIndex(r)
于 2014-04-04T18:33:52.527 回答
2

感谢布鲁斯的回答,我能够找到解决这个问题的方法,但是如果我从另一个文档中插入元素,我需要实际找到找到的文本的父级的索引,因为找到的文本只是里面的一个 Text 元素的段落元素。所以,我需要找到段落元素的索引,然后插入与该段落相关的新元素。

代码如下所示:

  var foundTag = body.findText(searchPattern);
  if (foundTag != null) {
    var tagElement = foundTag.getElement();
    var parent = tagElement.getParent();
    var insertPoint = parent.getParent().getChildIndex(parent);
    var otherBody = DocumentApp.openById(requirementsId).getActiveSection();
    var totalElements = otherBody.getNumChildren();

    for( var j = 0; j < totalElements; ++j ) {
    ... then same insertCode from the question above ...
      insertPoint++;
    }
于 2015-01-09T18:27:04.890 回答