高级文档服务

借助高级 Google 文档服务,您可以在 Apps 脚本中使用 Google 文档 API。与 Apps 脚本的内置 Google 文档服务非常相似,此 API 允许脚本读取、修改和设置 Google 文档中的内容格式。在大多数情况下,内置服务更易于使用,但此高级服务提供了一些额外的功能。

参考

如需详细了解此服务,请参阅 Docs API 的参考文档。与 Apps 脚本中的所有高级服务一样,高级 Google 文档服务使用的对象、方法和参数均与公共 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);
}

执行 - 使用更新数组调用 batchUpdate

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

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