将元素(表格)插入光标位置

时间:2015-04-17 08:08:31

标签: google-apps-script

我想创建一个具有自定义样式的新Table元素,并将其附加到文档中的当前光标位置。我看到有可能通过以下方式获得当前位置:

var cursor = DocumentApp.getActiveDocument().getCursor();

返回Position对象。 Position类提供了一种将Text附加到当前位置的方法:

cursor.insertText('ಠ‿ಠ');

但是从documentation我看不到插入通用元素(在我的情况下是一个表格)而不是简单文本的方法。

另一方面,Body类的方法允许将Table附加到文档的末尾,但是无法指定自定义位置。

有人可以帮忙吗?

由于

2 个答案:

答案 0 :(得分:0)

在其上插入STUB,例如。 cursor.insertText('%%MY_TABLE_WILL_GO_HERE%%');,然后继续函数找到这一行并放置表格。

答案 1 :(得分:0)

这就是我拼凑的方式。我有一个函数createComponentTable,它带有一个布尔值atCursor,如果为false,则在文档末尾追加一个表,如果为true,则在光标位置插入一个表。

(我在其他地方也可以使用功能doAlert(text),可以打开/关闭进行调试。)

function createComponentTable(atCursor) {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var thisTable;

  if (atCursor) {
    var cursor = doc.getCursor();
    if (cursor) {
      var element = cursor.getElement();
      if (element) {
        var parent = element.getParent();
        thisTable = body.insertTable(parent.getChildIndex(element) + 1);
      } else {
        doAlert('Cannot insert there');
      }
    } else {
      doAlert('Could not get cursor position');
    }
  } else {
    thisTable = body.appendTable();
  }

  if (thisTable) {
    // add rows and cells to thisTable here
  }
}
相关问题