Есть ли способ добавить шаблон документа поверх другого документа Google с помощью сценариев Google? - PullRequest
0 голосов
/ 16 июня 2019

Я пытаюсь добавить шаблон документа в существующий документ Google. Шаблон добавляется, но в следующий раз, когда я пытаюсь добавить шаблон снова, шаблон добавляется в нижней части существующего документа Google, но я хочу вставить шаблон вверху.

Это можно сделать, получив тело одного документа и добавив его дочерние элементы к текущему документу.

function addtemplate() {

  var thisDoc = DocumentApp.getActiveDocument();
  var thisBody = thisDoc.getBody();

  var templateDoc = DocumentApp.openById(''); //Pass in id of doc to be used as a template.
  var templateBody = templateDoc.getBody();

  for(var i=0; i<templateBody.getNumChildren();i++){ //run through the elements of the template doc's Body.
    switch (templateBody.getChild(i).getType()) { //Deal with the various types of Elements we will encounter and append.
      case DocumentApp.ElementType.PARAGRAPH:
        thisBody.appendParagraph(templateBody.getChild(i).copy());
        break;
      case DocumentApp.ElementType.LIST_ITEM:
        thisBody.appendListItem(templateBody.getChild(i).copy());
        break;
      case DocumentApp.ElementType.TABLE:
        thisBody.appendTable(templateBody.getChild(i).copy());
        break;
    }
  }

  return thisDoc;
}

1 Ответ

0 голосов
/ 17 июня 2019

Похоже, ваша цель состоит в том, чтобы выбрать позицию документа, в который добавляется контент?

Один из вариантов - добавить шаблон в текущее местоположение курсора.

В приведенном ниже примере у меня есть две функции.Первая функция создает меню в Google Docs, когда я открываю документ (обычно с задержкой в ​​несколько секунд).

Вторая функция пытается определить положение моего курсора.В случае успеха он вставит дату в моем положении курсора.

Поскольку я создал пункт меню, мне не нужно идти в редактор скриптов, чтобы вызвать эту функцию.

function onOpen() {
  // Add a menu item in Google Docs.
  DocumentApp.getUi().createMenu('Insert Menu')
      .addItem('Insert Current Date', 'insertCurrentDate')
      .addToUi();
}

function insertCurrentDate() {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  if (cursor) {
    // Attempt to insert text at the cursor position. If insertion returns null,
    // then the cursor's containing element doesn't allow text insertions.
    var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
    var element = cursor.insertText(date);
    if (element) {
      element.setBold(true);
    } else {
      DocumentApp.getUi().alert('Document does not allow inserted text at this location.');
    }
  } else {
    DocumentApp.getUi().alert('Cannot find a cursor in the document.');
  }
}

Также возможно, что вы хотите очистить предыдущий шаблон перед вставкой нового?Вы можете сделать это с помощью функции clear (), а затем запустить оставшуюся часть кода.

body.clear()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...