拡張ドキュメント サービス

高度なドキュメント サービスを使用すると、Apps Script で Google Docs API を使用できます。Apps Script に組み込まれている Google ドキュメント サービスと同様に、この API を使用すると、スクリプトで Google ドキュメントの内容の読み取り、編集、書式設定を行うことができます。ほとんどの場合、組み込みサービスの方が使いやすいですが、この高度なサービスにはいくつかの追加機能が用意されています。

リファレンス

このサービスの詳細については、Docs API のリファレンス ドキュメントをご覧ください。 Apps Script のすべての高度なサービスと同様に、高度なドキュメント サービスでも公開 API と同じオブジェクト、メソッド、パラメータを使用します。詳細については、メソッド シグネチャの決定方法をご覧ください。

問題を報告したり、その他のサポートを利用したりするには、Docs API サポートガイドをご覧ください。

サンプルコード

以下のサンプルコードでは、バージョン 1 の API を使用しています。

ドキュメントの作成

このサンプルでは新しいドキュメントを作成します。

advanced/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);
  }
}

テキストの検索や置換

このサンプルでは、ドキュメント内のテキストペアを検索して置換します。これは、テンプレート ドキュメントのコピー内のプレースホルダをデータベースの値に置き換える場合に便利です。

advanced/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);
  }
}

テキストの挿入とスタイル設定

このサンプルでは、ドキュメントの先頭に新しいテキストを挿入し、特定のフォントとサイズを使用している場合はスタイルを設定します。可能であれば、効率を上げるために複数のオペレーションを 1 つの batchUpdate 呼び出しにまとめるようにしてください。

advanced/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);
  }
}

第 1 段落を読み上げる

このサンプルでは、ドキュメントの最初の段落のテキストを記録します。ドキュメント API では段落の構造が構造化されているため、複数のサブ要素のテキストを結合する必要があります。

advanced/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 をループで呼び出すのではなく、複数のリクエストを 1 つの配列に結合します。

しない - batchUpdate をループで呼び出します。

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

推奨 - 更新の配列を指定して batchUpdate を呼び出します。

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

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