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

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

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

ดูข้อมูลอย่างละเอียดเกี่ยวกับบริการนี้ได้ในเอกสารประกอบอ้างอิงสำหรับ Docs API บริการเอกสารขั้นสูงจะใช้ออบเจ็กต์ เมธอด และพารามิเตอร์เดียวกันกับ 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() {
  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);
  }
}

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

ตัวอย่างนี้จะแทรกข้อความใหม่ไว้ที่ตอนต้นของเอกสารและรูปแบบหากมีแบบอักษรและขนาดที่เฉพาะเจาะจง โปรดทราบว่าหากเป็นไปได้ คุณควรจัดกลุ่มการดำเนินการหลายรายการเข้าด้วยกันเป็นการเรียก 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);
  }
}

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

ตัวอย่างนี้จะบันทึกข้อความในย่อหน้าแรกของเอกสาร เนื่องจากลักษณะของย่อหน้าใน Docs 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 แบบวนซ้ำ

ไม่ต้อง — เรียก 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);