고급 문서 서비스
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
고급 Docs 서비스를 사용하면 Apps Script에서 Google Docs API를 사용할 수 있습니다. Apps Script의 내장 Docs 서비스와 마찬가지로 이 API를 사용하면 스크립트가 Google Docs의 콘텐츠를 읽고, 수정하고, 서식을 지정할 수 있습니다. 대부분의 경우 기본 제공 서비스를 사용하는 것이 더 쉽지만 이 고급 서비스는 몇 가지 추가 기능을 제공합니다.
참조
이 서비스에 관한 자세한 내용은 Docs API의 참조 문서를 참고하세요.
Apps Script의 모든 고급 서비스와 마찬가지로 고급 Docs 서비스는 공개 API와 동일한 객체, 메서드, 매개변수를 사용합니다. 자세한 내용은 메서드 서명이 결정되는 방식을 참고하세요.
문제를 신고하고 기타 지원을 받으려면 Docs API 지원 가이드를 참고하세요.
샘플 코드
아래 샘플 코드에서는 API의 버전 1을 사용합니다.
문서 만들기
이 샘플에서는 새 문서를 만듭니다.
텍스트 찾기 및 바꾸기
이 샘플은 문서의 모든 탭에서 텍스트 쌍을 찾아 바꿉니다. 이는 템플릿 문서의 사본에 있는 자리표시자를 데이터베이스의 값으로 대체할 때 유용합니다.
텍스트 삽입 및 스타일 지정
이 샘플은 문서의 첫 번째 탭 시작 부분에 새 텍스트를 삽입하고 특정 글꼴과 크기로 스타일을 지정합니다. 가능한 경우 효율성을 위해 여러 작업을 단일 batchUpdate
호출로 일괄 처리해야 합니다.
첫 번째 단락 읽기
이 샘플은 문서의 첫 번째 탭에 있는 첫 번째 단락의 텍스트를 로깅합니다. Docs API의 단락은 구조화되어 있으므로 여러 하위 요소의 텍스트를 결합해야 합니다.
권장사항
일괄 업데이트
고급 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);
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-31(UTC)
[null,null,["최종 업데이트: 2025-08-31(UTC)"],[[["\u003cp\u003eThe advanced Docs service in Apps Script enables programmatic reading, editing, and formatting of Google Docs content using the Google Docs API.\u003c/p\u003e\n"],["\u003cp\u003eWhile often requiring the enabling of advanced services, it offers more features compared to the built-in Docs service.\u003c/p\u003e\n"],["\u003cp\u003eThis service mirrors the functionality of the public Docs API, allowing scripts to leverage its objects, methods, and parameters.\u003c/p\u003e\n"],["\u003cp\u003eSample code snippets are provided for tasks like creating documents, finding and replacing text, inserting and styling text, and reading paragraphs.\u003c/p\u003e\n"],["\u003cp\u003eFor optimal performance, batch multiple requests into a single \u003ccode\u003ebatchUpdate\u003c/code\u003e call instead of using loops.\u003c/p\u003e\n"]]],[],null,["# Advanced Docs Service\n\nThe advanced Docs service allows you to use the\n[Google Docs API](/docs/api) in Apps Script. Much like Apps Script's\n[built-in Docs service](/apps-script/reference/document),\nthis API allows scripts to read, edit, and format content in Google Docs. In\nmost cases the built-in service is easier to use, but this advanced service\nprovides a few extra features.\n| **Note:** This is an advanced service that you must [enable before use](/apps-script/guides/services/advanced). Follow the [quickstart](/docs/api/quickstart/apps-script) for step-by-step instructions on how to get started.\n\nReference\n---------\n\nFor detailed information on this service, see the\n[reference documentation](/docs/api/reference/rest) for the Docs API.\nLike all advanced services in Apps Script, the advanced Docs service uses the\nsame objects, methods, and parameters as the public API. For more information, see [How method signatures are determined](/apps-script/guides/services/advanced#how_method_signatures_are_determined).\n\nTo report issues and find other support, see the\n[Docs API support guide](/docs/api/support).\n\nSample code\n-----------\n\nThe sample code below uses [version 1](/docs/api/reference/rest) of the API.\n\n### Create document\n\nThis sample creates a new document. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```javascript\n/**\n * Create a new document.\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/create\n * @return {string} documentId\n */\nfunction createDocument() {\n try {\n // Create document with title\n const document = Docs.Documents.create({'title': 'My New Document'});\n console.log('Created document with ID: ' + document.documentId);\n return document.documentId;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', e.message);\n }\n}\n```\n\nFind and replace text\n---------------------\n\nThis sample finds and replaces pairs of text across all tabs in a document. This\ncan be useful when replacing placeholders in a copy of a template document with\nvalues from a database. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```javascript\n/**\n * Performs \"replace all\".\n * @param {string} documentId The document to perform the replace text operations on.\n * @param {Object} findTextToReplacementMap A map from the \"find text\" to the \"replace text\".\n * @return {Object} replies\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate\n */\nfunction findAndReplace(documentId, findTextToReplacementMap) {\n const requests = [];\n for (const findText in findTextToReplacementMap) {\n const replaceText = findTextToReplacementMap[findText];\n // One option for replacing all text is to specify all tab IDs.\n const request = {\n replaceAllText: {\n containsText: {\n text: findText,\n matchCase: true\n },\n replaceText: replaceText,\n tabsCriteria: {\n tabIds: [TAB_ID_1, TAB_ID_2, TAB_ID_3],\n }\n }\n };\n // Another option is to omit TabsCriteria if you are replacing across all tabs.\n const request = {\n replaceAllText: {\n containsText: {\n text: findText,\n matchCase: true\n },\n replaceText: replaceText\n }\n };\n requests.push(request);\n }\n try {\n const response = Docs.Documents.batchUpdate({'requests': requests}, documentId);\n const replies = response.replies;\n for (const [index] of replies.entries()) {\n const numReplacements = replies[index].replaceAllText.occurrencesChanged || 0;\n console.log('Request %s performed %s replacements.', index, numReplacements);\n }\n return replies;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error : %s', e.message);\n }\n}\n```\n\nInsert and style text\n---------------------\n\nThis sample inserts new text at the start of the first tab in the document and\nstyles it with a specific font and size. Note that when possible you should\nbatch together multiple operations into a single `batchUpdate` call for\nefficiency. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```javascript\n/**\n * Insert text at the beginning of the first tab in the document and then style\n * the inserted text.\n * @param {string} documentId The document the text is inserted into.\n * @param {string} text The text to insert into the document.\n * @return {Object} replies\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate\n */\nfunction insertAndStyleText(documentId, text) {\n const requests = [{\n insertText: {\n location: {\n index: 1,\n // A tab can be specified using its ID. When omitted, the request is\n // applied to the first tab.\n // tabId: TAB_ID\n },\n text: text\n }\n },\n {\n updateTextStyle: {\n range: {\n startIndex: 1,\n endIndex: text.length + 1\n },\n textStyle: {\n fontSize: {\n magnitude: 12,\n unit: 'PT'\n },\n weightedFontFamily: {\n fontFamily: 'Calibri'\n }\n },\n fields: 'weightedFontFamily, fontSize'\n }\n }];\n try {\n const response =Docs.Documents.batchUpdate({'requests': requests}, documentId);\n return response.replies;\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with an error %s', e.message);\n }\n}\n```\n\nRead first paragraph\n--------------------\n\nThis sample logs the text of the first paragraph of the first tab in the\ndocument. Because of the structured nature of paragraphs in the\nDocs API, this involves combining the text of multiple sub-elements. \nadvanced/docs.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/docs.gs) \n\n```javascript\n/**\n * Read the first paragraph of the first tab in a document.\n * @param {string} documentId The ID of the document to read.\n * @return {Object} paragraphText\n * @see https://developers.google.com/docs/api/reference/rest/v1/documents/get\n */\nfunction readFirstParagraph(documentId) {\n try {\n // Get the document using document ID\n const document = Docs.Documents.get(documentId, {'includeTabsContent': true});\n const firstTab = document.tabs[0];\n const bodyElements = firstTab.documentTab.body.content;\n for (let i = 0; i \u003c bodyElements.length; i++) {\n const structuralElement = bodyElements[i];\n // Print the first paragraph text present in document\n if (structuralElement.paragraph) {\n const paragraphElements = structuralElement.paragraph.elements;\n let paragraphText = '';\n\n for (let j = 0; j \u003c paragraphElements.length; j++) {\n const paragraphElement = paragraphElements[j];\n if (paragraphElement.textRun !== null) {\n paragraphText += paragraphElement.textRun.content;\n }\n }\n console.log(paragraphText);\n return paragraphText;\n }\n }\n } catch (e) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', e.message);\n }\n}\n```\n\nBest Practices\n--------------\n\n### Batch Updates\n\nWhen using the advanced Docs service, combine multiple requests in an array\nrather than calling `batchUpdate` in a loop.\n\nDon't --- Call `batchUpdate` in a loop. \n\n var textToReplace = ['foo', 'bar'];\n for (var i = 0; i \u003c textToReplace.length; i++) {\n Docs.Documents.batchUpdate({\n requests: [{\n replaceAllText: ...\n }]\n }, docId);\n }\n\nDo --- Call `batchUpdate` with an array of\nupdates. \n\n var requests = [];\n var textToReplace = ['foo', 'bar'];\n for (var i = 0; i \u003c textToReplace.length; i++) {\n requests.push({ replaceAllText: ... });\n }\n\n Docs.Documents.batchUpdate({\n requests: requests\n }, docId);"]]