บริการเอกสารขั้นสูง

บริการ Docs ขั้นสูงช่วยให้คุณใช้ Google Docs API ใน Google Apps Script ได้ API นี้ช่วยให้สคริปต์อ่าน แก้ไข และจัดรูปแบบเนื้อหาใน Google Docs ได้เช่นเดียวกับบริการ Docs ในตัวของ Apps Script's ในกรณีส่วนใหญ่ บริการในตัวจะใช้งานง่ายกว่า แต่บริการขั้นสูงนี้มีฟีเจอร์เพิ่มเติมบางอย่าง

นี่คือบริการขั้นสูงที่คุณต้อง เปิดใช้ก่อนใช้งาน ทำตาม คู่มือเริ่มต้นฉบับย่อเพื่อดูวิธีการทีละขั้นตอน ในการเริ่มต้นใช้งาน

ข้อมูลอ้างอิง

ดูข้อมูลโดยละเอียดเกี่ยวกับบริการนี้ได้ใน เอกสารอ้างอิงสำหรับ Docs API บริการ Docs ขั้นสูงใช้ฟังก์ชันออบเจ็กต์ เมธอด และพารามิเตอร์เดียวกันกับ API สาธารณะ เช่นเดียวกับบริการขั้นสูงทั้งหมดใน Apps Script ดูข้อมูลเพิ่มเติมได้ที่ หัวข้อวิธีกำหนดลายเซ็นเมธอด

หากต้องการรายงานปัญหาและดูการสนับสนุนอื่นๆ โปรดดู คู่มือการสนับสนุน 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() {
  // Create document with title
  const document = Docs.Documents.create({ title: "My New Document" });
  console.log(`Created document with ID: ${document.documentId}`);
  return document.documentId;
}

ค้นหาและแทนที่ข้อความ

ตัวอย่างนี้จะค้นหาและแทนที่ข้อความที่จับคู่กันในแท็บทั้งหมดของเอกสาร ซึ่งจะเป็นประโยชน์เมื่อแทนที่ตัวยึดตำแหน่งในสำเนาเอกสารเทมเพลตด้วยค่าจากฐานข้อมูล

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];

    // Replace all text across all tabs.
    const replaceAllTextRequest = {
      replaceAllText: {
        containsText: {
          text: findText,
          matchCase: true,
        },
        replaceText: replaceText,
      },
    };

    // Replace all text across specific tabs.
    const _replaceAllTextWithTabsCriteria = {
      replaceAllText: {
        ...replaceAllTextRequest.replaceAllText,
        tabsCriteria: {
          tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],
        },
      },
    };
    requests.push(replaceAllTextRequest);
  }
  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;
}

แทรกและจัดรูปแบบข้อความ

ตัวอย่างนี้จะแทรกข้อความใหม่ที่จุดเริ่มต้นของแท็บแรกในเอกสารและจัดรูปแบบข้อความด้วยฟอนต์และขนาดที่เฉพาะเจาะจง โปรดทราบว่าคุณควรจัดกลุ่มการดำเนินการหลายรายการไว้ในการเรียก 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",
      },
    },
  ];
  const response = Docs.Documents.batchUpdate(
    { requests: requests },
    documentId,
  );
  return response.replies;
}

อ่านย่อหน้าแรก

ตัวอย่างนี้จะบันทึกข้อความของย่อหน้าแรกในแท็บแรกของเอกสาร เนื่องจากย่อหน้าใน 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) {
  // 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;
    }
  }
}

แนวทางปฏิบัติแนะนำ

การอัปเดตเป็นกลุ่ม

เมื่อใช้บริการ Docs ขั้นสูง ให้รวมคำขอหลายรายการไว้ในอาร์เรย์แทนการเรียก 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);