Расширенная служба документов

Расширенная служба Документов позволяет использовать API Документов Google в скриптах приложений. Подобно встроенному сервису Docs Apps Script, этот API позволяет сценариям читать, редактировать и форматировать контент в Документах Google. В большинстве случаев встроенную службу проще использовать, но эта расширенная служба предоставляет несколько дополнительных функций.

Ссылка

Подробную информацию об этом сервисе можно найти в справочной документации API Документов. Как и все расширенные службы в Apps Script, расширенная служба Документов использует те же объекты, методы и параметры, что и общедоступный API. Дополнительные сведения см. в разделе Как определяются сигнатуры методов .

Чтобы сообщить о проблемах и получить другую поддержку, ознакомьтесь с руководством по поддержке Docs API .

Образец кода

В приведенном ниже примере кода используется версия 1 API.

Создать документ

В этом примере создается новый документ.

расширенный/docs.gs
/**
 * Create a new document.
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create
 * @return {string} documentId
 */
function createDocument() {
  try {
    // Create document with title
    const document = Docs.Documents.create({'title': 'My New Document'});
    console.log('Created document with ID: ' + document.documentId);
    return document.documentId;
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', e.message);
  }
}

Найти и заменить текст

Этот пример находит и заменяет пары текста в документе. Это может быть полезно при замене заполнителей в копии документа-шаблона значениями из базы данных.

расширенный/docs.gs
/**
 * Performs "replace all".
 * @param {string} documentId The document to perform the replace text operations on.
 * @param {Object} findTextToReplacementMap A map from the "find text" to the "replace text".
 * @return {Object} replies
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
 */
function findAndReplace(documentId, findTextToReplacementMap) {
  const requests = [];
  for (const findText in findTextToReplacementMap) {
    const replaceText = findTextToReplacementMap[findText];
    const request = {
      replaceAllText: {
        containsText: {
          text: findText,
          matchCase: true
        },
        replaceText: replaceText
      }
    };
    requests.push(request);
  }
  try {
    const response = Docs.Documents.batchUpdate({'requests': requests}, documentId);
    const replies = response.replies;
    for (const [index] of replies.entries()) {
      const numReplacements = replies[index].replaceAllText.occurrencesChanged || 0;
      console.log('Request %s performed %s replacements.', index, numReplacements);
    }
    return replies;
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error : %s', e.message);
  }
}

Вставка и оформление текста

В этом примере новый текст вставляется в начало документа и стилизуется, если используется определенный шрифт и размер. Обратите внимание: по возможности вам следует объединить несколько операций в один вызов batchUpdate для повышения эффективности.

расширенный/docs.gs
/**
 * Insert text at the beginning of the document and then style the inserted
 * text.
 * @param {string} documentId The document the text is inserted into.
 * @param {string} text The text to insert into the document.
 * @return {Object} replies
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate
 */
function insertAndStyleText(documentId, text) {
  const requests = [{
    insertText: {
      location: {
        index: 1
      },
      text: text
    }
  },
  {
    updateTextStyle: {
      range: {
        startIndex: 1,
        endIndex: text.length + 1
      },
      textStyle: {
        fontSize: {
          magnitude: 12,
          unit: 'PT'
        },
        weightedFontFamily: {
          fontFamily: 'Calibri'
        }
      },
      fields: 'weightedFontFamily, fontSize'
    }
  }];
  try {
    const response =Docs.Documents.batchUpdate({'requests': requests}, documentId);
    return response.replies;
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with an error %s', e.message);
  }
}

Прочитай первый абзац

В этом примере регистрируется текст первого абзаца документа. Из-за структурированного характера абзацев в API Документов это предполагает объединение текста нескольких подэлементов.

расширенный/docs.gs
/**
 * Read the first paragraph of the body of a document.
 * @param {string} documentId The ID of the document to read.
 * @return {Object} paragraphText
 * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get
 */
function readFirstParagraph(documentId) {
  try {
    // Get the document using document ID
    const document = Docs.Documents.get(documentId);
    const bodyElements = document.body.content;
    for (let i = 0; i < bodyElements.length; i++) {
      const structuralElement = bodyElements[i];
      // Print the first paragraph text present in document
      if (structuralElement.paragraph) {
        const paragraphElements = structuralElement.paragraph.elements;
        let paragraphText = '';

        for (let j = 0; j < paragraphElements.length; j++) {
          const paragraphElement = paragraphElements[j];
          if (paragraphElement.textRun !== null) {
            paragraphText += paragraphElement.textRun.content;
          }
        }
        console.log(paragraphText);
        return paragraphText;
      }
    }
  } catch (e) {
    // TODO (developer) - Handle exception
    console.log('Failed with error %s', e.message);
  }
}

Лучшие практики

Пакетные обновления

При использовании расширенной службы Документов объединяйте несколько запросов в массив, а не вызывайте batchUpdate в цикле.

Не делайте этого — вызывайте batchUpdate в цикле.

var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
  Docs.Documents.batchUpdate({
    requests: [{
      replaceAllText: ...
    }]
  }, docId);
}

Do — вызвать batchUpdate с массивом обновлений.

var requests = [];
var textToReplace = ['foo', 'bar'];
for (var i = 0; i < textToReplace.length; i++) {
  requests.push({ replaceAllText: ... });
}

Docs.Documents.batchUpdate({
  requests: requests
}, docId);