insertListItem(index,text)错误的索引

时间:2013-09-16 16:04:25

标签: google-apps-script

我正在尝试使用Google Apps脚本将文本替换为文档模板,并将其另存为.pdf。我大部分都成功了,但我遇到了一个问题。我希望脚本能够在模板中搜索文本,使用项目符号替换文本和提供的文本。它将忽略可能放入文本的任何额外\ n。这是一个示例文本:

Today was a good day.
Tomorrow will be a good day.

Yesterday was a decent day.

在我的文档中,我希望文本在一行中替换_text_Comments: _text_。最终,打印出来的内容如下:

Comments:
- Today was a good day.
- Tomorrow will be a good day.
- Yesteday was a decent day.

这是我到目前为止的代码,但它运行得不太顺利。如果有人能提供任何帮助,我们将不胜感激。

var listr = "";
var trunc = text.split("\n"); \\ where text is to be placed into the template
var index = b.findText("_text_").getStartOffset(); \\ var b is getBody()
for (var j = (trunc.length - 1); j >= 0; j--)
  if(!trunc[j].equals("")) b.insertListItem(index, trunc[j]);
b.replaceText("_text_", "");

非常感谢任何帮助。我最难理解Google Docs中索引的概念。谢谢。


您好。只是想让你知道我最终如何实现这个:

var trunc = text.split("\n"); \\where text is to be placed into the template
var index = b.getChildIndex(b.findText("foo").getElement().getParent()) + 1;
for (var j = (trunc.length - 1); j >= 0; j--)
  if (trunc[j] != "") b.insertListItem(index, trunc[j]);

希望有所帮助。它将元素向后推回到彼此。

1 个答案:

答案 0 :(得分:0)

好的,这个粗略的代码似乎插入了包含TEXT的PARAGRAPH的开头,TEXT似乎是一个单独的子元素。可能这个特定的代码只有在文本不在子表,子列表等中时才有效...但也许它会有所帮助。

var element = DocumentApp.create('newDoc').getBody()
  .appendListItem('testing').copy();
var index = b.getChildIndex(
  b.findText('_text_').getElement().getParent().asParagraph() );
b.insertListItem(index, element);

我度过了漫长的一天,也许我以后可以改进它,大多数我认为缺少的是getChildIndex()函数。同样使用newDoc的insertListItem()有一些奇怪的“元素必须分离”。消息,直到我使用.copy()所以请注意那里。