/** * Create a new document. * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create * @return {string} documentId */functioncreateDocument(){try{// Create document with titleconstdocument=Docs.Documents.create({'title':'My New Document'});console.log('Created document with ID: '+document.documentId);returndocument.documentId;}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failed with error %s',e.message);}}
/** * 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 %s performed %s replacements.',index,numReplacements);}returnreplies;}catch(e){// TODO (developer) - Handle exceptionconsole.log('Failed with error : %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('Failed with an error %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('Failed with error %s',e.message);}}
[[["容易理解","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-08-01 (世界標準時間)。"],[[["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."]]],[]]