Dịch vụ Tài liệu nâng cao

Dịch vụ Tài liệu nâng cao cho phép bạn sử dụng API Google Tài liệu trong Apps Script. Giống như dịch vụ Tài liệu tích hợp sẵn của Apps Script, API này cho phép tập lệnh đọc, chỉnh sửa và định dạng nội dung trong Google Tài liệu. Trong hầu hết các trường hợp, dịch vụ tích hợp sẵn sẽ dễ dùng hơn, nhưng dịch vụ nâng cao này cung cấp thêm một vài tính năng.

Tài liệu tham khảo

Để biết thông tin chi tiết về dịch vụ này, hãy xem tài liệu tham khảo dành cho API Tài liệu. Giống như tất cả các dịch vụ nâng cao trong Apps Script, dịch vụ Tài liệu nâng cao sử dụng cùng đối tượng, phương thức và tham số như API công khai. Để biết thêm thông tin, hãy xem phần Cách xác định chữ ký phương thức.

Để báo cáo sự cố và tìm dịch vụ hỗ trợ khác, hãy xem Hướng dẫn hỗ trợ API Tài liệu.

Mã mẫu

Mã mẫu bên dưới sử dụng phiên bản 1 của API.

Tạo tài liệu

Mẫu này sẽ tạo một tài liệu mới.

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

Tìm và thay thế văn bản

Mẫu này sẽ tìm và thay thế các cặp văn bản trong một tài liệu. Việc này có thể hữu ích khi thay thế phần giữ chỗ trong bản sao của tài liệu mẫu bằng các giá trị từ một cơ sở dữ liệu.

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

Chèn và tạo kiểu cho văn bản

Mẫu này sẽ chèn văn bản mới vào đầu tài liệu và các kiểu nếu có phông chữ và kích thước cụ thể. Xin lưu ý rằng khi có thể, bạn nên kết hợp nhiều thao tác thành một lệnh gọi batchUpdate để tăng tính hiệu quả.

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

Đọc đoạn đầu tiên

Mẫu này sẽ ghi lại văn bản của đoạn đầu tiên trong tài liệu. Do tính chất có cấu trúc của các đoạn văn trong API Tài liệu, nên cần phải kết hợp văn bản của nhiều phần tử phụ.

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

Những phương pháp hay nhất

Cập nhật theo lô

Khi sử dụng dịch vụ Tài liệu nâng cao, hãy kết hợp nhiều yêu cầu trong một mảng thay vì gọi batchUpdate trong một vòng lặp.

Không nên — Gọi batchUpdate trong một vòng lặp.

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

Do (Nên làm) – Gọi batchUpdate với một loạt các nội dung cập nhật.

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

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