進階文件服務

進階 Docs 服務可讓您在 Apps Script 中使用 Google Docs API。這個 API 與 Apps Script 的內建 Google 文件服務非常相似,可讓指令碼讀取、編輯及設定 Google 文件中的內容格式。在大多數情況下,內建服務的使用方式較為簡單,但這項進階服務提供一些額外功能。

參考資料

如需這項服務的詳細資訊,請參閱 Docs API 的參考說明文件。與 Apps Script 中的所有進階服務一樣,進階 Docs 服務會使用與公開 API 相同的物件、方法和參數。詳情請參閱「如何決定方法簽章」。

如要回報問題並尋求其他支援,請參閱 Docs API 支援手冊

程式碼範例

以下程式碼範例使用 API 的 第 1 版

建立文件

此範例會建立新文件。

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];
    // One option for replacing all text is to specify all tab IDs.
    const request = {
      replaceAllText: {
        containsText: {
          text: findText,
          matchCase: true
        },
        replaceText: replaceText,
        tabsCriteria: {
          tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],
        }
      }
    };
    // Another option is to omit TabsCriteria if you are replacing across all tabs.
    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 呼叫。

advanced/docs.gs
/**
 * Insert text at the beginning of the first tab in 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,
        // A tab can be specified using its ID. When omitted, the request is
        // applied to the first tab.
        // tabId: TAB_ID
      },
      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);
  }
}

朗讀第一段

這個範例會記錄文件中第一個分頁第一段落的文字。由於 Docs API 中的段落具有結構化特性,因此這項操作需要結合多個子元素的文字。

advanced/docs.gs
/**
 * Read the first paragraph of the first tab in 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, {'includeTabsContent': true});
    const firstTab = document.tabs[0];
    const bodyElements = firstTab.documentTab.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);
  }
}

最佳做法

批次更新

使用進階的 Google 文件服務時,請在陣列中合併多個要求,而非在迴圈中呼叫 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);