您可以在 Docs 進階服務中使用 Google Docs API 在 Apps Script 中。這個 API 與 Apps Script 的內建 Google 文件服務非常相似,可讓指令碼讀取、編輯及設定 Google 文件中的內容格式。在大多數情況下,內建服務的使用方式較為簡單,但這項進階服務提供一些額外功能。
參考資料
如要進一步瞭解這項服務,請參閱 Docs API 的參考說明文件。與 Apps Script 中的所有進階服務一樣,進階 Docs 服務會使用與公開 API 相同的物件、方法和參數。詳情請參閱「如何決定方法簽章」。
/** * 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 */functionfindAndReplace(documentId,findTextToReplacementMap){constrequests=[];for(constfindTextinfindTextToReplacementMap){constreplaceText=findTextToReplacementMap[findText];// One option for replacing all text is to specify all tab IDs.constrequest={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.constrequest={replaceAllText:{containsText:{text:findText,matchCase:true},replaceText:replaceText}};requests.push(request);}try{constresponse=Docs.Documents.batchUpdate({'requests':requests},documentId);constreplies=response.replies;for(const[index]ofreplies.entries()){constnumReplacements=replies[index].replaceAllText.occurrencesChanged||0;console.log('Request%sperformed%sreplacements.',index,numReplacements);}returnreplies;}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failedwitherror:%s',e.message);}}
/** * 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 */functioninsertAndStyleText(documentId,text){constrequests=[{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{constresponse=Docs.Documents.batchUpdate({'requests':requests},documentId);returnresponse.replies;}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failedwithanerror%s',e.message);}}
朗讀第一段
這個範例會記錄文件中第一個分頁第一段落的文字。由於 Docs API 中的段落具有結構化特性,因此這項操作需要結合多個子元素的文字。
/** * 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 */functionreadFirstParagraph(documentId){try{// Get the document using document IDconstdocument=Docs.Documents.get(documentId,{'includeTabsContent':true});constfirstTab=document.tabs[0];constbodyElements=firstTab.documentTab.body.content;for(leti=0;i < bodyElements.length;i++){conststructuralElement=bodyElements[i];// Print the first paragraph text present in documentif(structuralElement.paragraph){constparagraphElements=structuralElement.paragraph.elements;letparagraphText='';for(letj=0;j < paragraphElements.length;j++){constparagraphElement=paragraphElements[j];if(paragraphElement.textRun!==null){paragraphText+=paragraphElement.textRun.content;}}console.log(paragraphText);returnparagraphText;}}}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failedwitherror%s',e.message);}}
最佳做法
批次更新
使用進階的 Google 文件服務時,請在陣列中合併多個要求,而非在迴圈中呼叫 batchUpdate。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-06-05 (世界標準時間)。"],[[["The advanced Docs service in Apps Script enables programmatic reading, editing, and formatting of Google Docs content using the Google Docs API."],["While often requiring the enabling of advanced services, it offers more features compared to the built-in Docs service."],["This service mirrors the functionality of the public Docs API, allowing scripts to leverage its objects, methods, and parameters."],["Sample code snippets are provided for tasks like creating documents, finding and replacing text, inserting and styling text, and reading paragraphs."],["For optimal performance, batch multiple requests into a single `batchUpdate` call instead of using loops."]]],[]]