/** * 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"]],["最后更新时间 (UTC):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."]]],[]]