如何使用Google Apps Script for Docs将光标移动到文档的开头?
我正在使用Google文档编写Google Apps脚本脚本,并想知道如何将光标移动到文档的开头。
我最后想要做的只是用一些字符串替换第一行。
I am writing a script of Google Apps Script with my Google Document and wondering how to move the cursor to the very beginning of the document. What I was trying to do at the end is just replace the first line with some string.
这很简单,您可以使用 setCursor()
方法记录在这里。
This is very simple, you can use the setCursor()
method documented here.
示例代码:
Example code :
function setCursorToStart() {
var doc = DocumentApp.getActiveDocument();
var paragraph = doc.getBody().getChild(0);
var position = doc.newPosition(paragraph.getChild(0), 0);
doc.setCursor(position);
}
这会将光标位置设置为文档的开头,但是在您的问题中你说你想在这个位置插入一些数据,那么实际的光标位置是不相关的,你可以在那里插入一个字符串,而不必移动光标。示例代码:
This will set the cursor position to the start of your document but in your question you say you want to insert some data at this position, then the actual cursor position is irrelevant, you can insert a string there without necessarily moving the cursor . Example code :
function insertTextOnTop() {
var doc = DocumentApp.getActiveDocument();
var top = doc.getBody().getChild(0);
top.asParagraph().insertText(0,'text to insert');
doc.saveAndClose();
}