Google Docs API의 유용한 애플리케이션 중 하나는 하나 이상의 데이터 소스의 정보를 문서로 병합하는 것입니다.
이 페이지에서는 외부 소스의 데이터를 가져와 기존 템플릿 문서에 삽입하는 방법을 설명합니다.
템플릿은 템플릿에서 생성된 모든 문서에 동일한 고정 텍스트가 포함된 특수한 유형의 문서로, 다른 동적 텍스트를 배치할 수 있는 지정된 자리표시자가 함께 포함됩니다. 예를 들어 계약 템플릿에는 수신자의 이름, 주소, 기타 세부정보를 위한 자리와 함께 고정된 콘텐츠가 있을 수 있습니다. 그런 다음 앱에서 고객별 데이터를 템플릿에 병합하여 완성된 문서를 만들 수 있습니다.
이 접근 방식이 유용한 이유는 다음과 같습니다.
디자이너는 Google Docs 편집기를 사용하여 문서의 디자인을 쉽게 미세 조정할 수 있습니다. 앱에서 매개변수를 조정하여 렌더링된 레이아웃을 설정하는 것보다 훨씬 쉽습니다.
콘텐츠와 프레젠테이션을 분리하는 것은 많은 이점이 있는 잘 알려진 디자인 원칙입니다.
기본 레시피
다음은 Docs API를 사용하여 데이터를 문서에 병합하는 방법의 예입니다.
디자인과 형식을 정하는 데 도움이 되도록 자리표시자 콘텐츠를 사용하여 문서를 만듭니다. 바꾸려는 텍스트 서식은 유지됩니다.
삽입할 각 요소에 대해 자리표시자 콘텐츠를 태그로 바꿉니다. 일반적으로 발생하지 않을 문자열을 사용해야 합니다. 예를 들어 {{account-holder-name}}이 좋은 태그일 수 있습니다.
템플릿의 모든 탭에서 2개의 필드를 실제 값으로 대체하여 완성된 문서를 생성하는 다음 예시를 참고하세요.
이 병합을 수행하려면 아래 코드를 사용하면 됩니다.
자바
StringcustomerName="Alice";DateTimeFormatterformatter=DateTimeFormatter.ofPattern("yyyy/MM/dd");Stringdate=formatter.format(LocalDate.now());List<Request>requests=newArrayList<>();// One option for replacing all text is to specify all tab IDs.requests.add(newRequest().setReplaceAllText(newReplaceAllTextRequest().setContainsText(newSubstringMatchCriteria().setText("{{customer-name}}").setMatchCase(true)).setReplaceText(customerName).setTabsCriteria(newTabsCriteria().addTabIds(TAB_ID_1).addTabIds(TAB_ID_2).addTabIds(TAB_ID_3))));// Another option is to omit TabsCriteria if you are replacing across all tabs.requests.add(newRequest().setReplaceAllText(newReplaceAllTextRequest().setContainsText(newSubstringMatchCriteria().setText("{{date}}").setMatchCase(true)).setReplaceText(date)));BatchUpdateDocumentRequestbody=newBatchUpdateDocumentRequest();service.documents().batchUpdate(documentId,body.setRequests(requests)).execute();
Node.js
letcustomerName='Alice';letdate=yyyymmdd()letrequests=[// One option for replacing all text is to specify all tab IDs.{replaceAllText:{containsText:{text:'{{customer-name}}',matchCase:true,},replaceText:customerName,tabsCriteria:{tabIds:[TAB_ID_1,TAB_ID_2,TAB_ID_3],},},},// Another option is to omit TabsCriteria if you are replacing across all tabs.{replaceAllText:{containsText:{text:'{{date}}',matchCase:true,},replaceText:date,},},];google.options({auth:auth});google.discoverAPI('https://docs.googleapis.com/$discovery/rest?version=v1&key={YOUR_API_KEY}').then(function(docs){docs.documents.batchUpdate({documentId:'1yBx6HSnu_gbV2sk1nChJOFo_g3AizBhr-PpkyKAwcTg',resource:{requests,},},(err,{data})=>{if(err)returnconsole.log('The API returned an error: '+err);console.log(data);});});
Python
customer_name='Alice'date=datetime.datetime.now().strftime("%y/%m/%d")requests=[# One option for replacing all text is to specify all tab IDs.{'replaceAllText':{'containsText':{'text':'{{customer-name}}','matchCase':'true'},'replaceText':customer_name,'tabsCriteria':{'tabIds':[TAB_ID_1,TAB_ID_2,TAB_ID_3],},}},# Another option is to omit TabsCriteria if you are replacing across all tabs.{'replaceAllText':{'containsText':{'text':'{{date}}','matchCase':'true'},'replaceText':str(date),}}]result=service.documents().batchUpdate(documentId=document_id,body={'requests':requests}).execute()
템플릿 관리
애플리케이션이 정의하고 소유하는 템플릿 문서의 경우 애플리케이션을 나타내는 전용 계정을 사용하여 템플릿을 만듭니다.
서비스 계정을 사용하면 공유를 제한하는 Google Workspace 정책과 관련된 복잡한 문제를 피할 수 있습니다.
템플릿에서 문서 인스턴스를 만들 때는 항상 최종 사용자 인증 정보를 사용하세요. 이렇게 하면 사용자가 결과 문서를 완전히 제어할 수 있으며 Drive의 사용자별 한도와 관련된 확장 문제가 방지됩니다.
서비스 계정을 사용하여 템플릿을 만들려면 애플리케이션 사용자 인증 정보로 다음 단계를 실행하세요.
[[["이해하기 쉬움","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-29(UTC)"],[],[],null,["# Merge text into a document\n\nOne useful application of the Google Docs API is to merge information from one\nor more data sources into a document.\n\nThis page outlines how you can take data from an external source and insert it\ninto an existing template document.\n\nA *template* is a special type of document containing the same fixed text for\nall documents created from the template, along with designated placeholders\nwhere other dynamic text can be placed. For example, a contract template might\nhave fixed content, along with spots for the receiver's name, address, and other\ndetails. Your app can then merge customer-specific data into the template to\ncreate finished documents.\n\nThere are several reasons why this approach is useful:\n\n- It's easy for designers to fine-tune a document's design using the\n Google Docs editor. This is much easier than tuning parameters in your app\n to set the rendered layout.\n\n- Separating content from presentation is a well-known design principle with\n many benefits.\n\nA basic recipe\n--------------\n\nHere's an example of how you can use the Docs API to merge data into a\ndocument:\n\n1. Create your document using placeholder content to help you with the design\n and format. Any text formatting you want to replace is preserved.\n\n2. For each element you'll be inserting, replace the placeholder content with a\n tag. Be sure to use strings that are unlikely to occur normally. For\n example,\n `{{account-holder-name}}` might be a good tag.\n\n3. In your code, use the Google Drive API to make a copy of the document.\n\n4. In your code, use the Docs API's\n [`batchUpdate()`](/workspace/docs/api/reference/rest/v1/documents/batchUpdate)\n method with the document name and include a\n [`ReplaceAllTextRequest`](/workspace/docs/api/reference/rest/v1/documents/request#replacealltextrequest).\n\nDocument IDs reference a document and they can be derived from the URL \n\n```\nhttps://docs.google.com/document/d/documentId/edit\n```\n| You can perform multiple replacements in the same BatchUpdate request for efficiency. See [batch request best practices](/workspace/docs/api/how-tos/batch) for how to batch API calls together\n\nExample\n-------\n\nConsider the following example, which replaces 2 fields across all tabs of a\ntemplate with real values to generate a finished document.\n\nTo perform this merge, you can use the code below. \n\n### Java\n\n```java\nString customerName = \"Alice\";\nDateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy/MM/dd\");\nString date = formatter.format(LocalDate.now());\n\nList\u003cRequest\u003e requests = new ArrayList\u003c\u003e();\n// One option for replacing all text is to specify all tab IDs.\nrequests.add(new Request()\n .setReplaceAllText(new ReplaceAllTextRequest()\n .setContainsText(new SubstringMatchCriteria()\n .setText(\"{{customer-name}}\")\n .setMatchCase(true))\n .setReplaceText(customerName)\n .setTabsCriteria(new TabsCriteria()\n .addTabIds(TAB_ID_1)\n .addTabIds(TAB_ID_2)\n .addTabIds(TAB_ID_3))));\n// Another option is to omit TabsCriteria if you are replacing across all tabs.\nrequests.add(new Request()\n .setReplaceAllText(new ReplaceAllTextRequest()\n .setContainsText(new SubstringMatchCriteria()\n .setText(\"{{date}}\")\n .setMatchCase(true))\n .setReplaceText(date)));\n\nBatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();\nservice.documents().batchUpdate(documentId, body.setRequests(requests)).execute();\n```\n\n### Node.js\n\n```javascript\n let customerName = 'Alice';\n let date = yyyymmdd()\n let requests = [\n // One option for replacing all text is to specify all tab IDs.\n {\n replaceAllText: {\n containsText: {\n text: '{{customer-name}}',\n matchCase: true,\n },\n replaceText: customerName,\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 {\n replaceAllText: {\n containsText: {\n text: '{{date}}',\n matchCase: true,\n },\n replaceText: date,\n },\n },\n ];\n\n google.options({auth: auth});\n google\n .discoverAPI(\n 'https://docs.googleapis.com/$discovery/rest?version=v1&key={YOUR_API_KEY}')\n .then(function(docs) {\n docs.documents.batchUpdate(\n {\n documentId: '1yBx6HSnu_gbV2sk1nChJOFo_g3AizBhr-PpkyKAwcTg',\n resource: {\n requests,\n },\n },\n (err, {data}) =\u003e {\n if (err) return console.log('The API returned an error: ' + err);\n console.log(data);\n });\n });\n```\n\n### Python\n\n```python\ncustomer_name = 'Alice'\ndate = datetime.datetime.now().strftime(\"%y/%m/%d\")\n\nrequests = [\n # One option for replacing all text is to specify all tab IDs.\n {\n 'replaceAllText': {\n 'containsText': {\n 'text': '{{customer-name}}',\n 'matchCase': 'true'\n },\n 'replaceText': customer_name,\n 'tabsCriteria': {\n 'tabIds': [TAB_ID_1, TAB_ID_2, TAB_ID_3],\n },\n }},\n # Another option is to omit TabsCriteria if you are replacing across all tabs.\n {\n 'replaceAllText': {\n 'containsText': {\n 'text': '{{date}}',\n 'matchCase': 'true'\n },\n 'replaceText': str(date),\n }\n }\n]\n\nresult = service.documents().batchUpdate(\n documentId=document_id, body={'requests': requests}).execute()\n```\n| **Note:** For documents with multiple [tabs](/workspace/docs/api/how-tos/tabs), [`ReplaceAllTextRequest`](/workspace/docs/api/reference/rest/v1/documents/request#replacealltextrequest) by default applies to all tabs. See the request documentation for more information about how to work with tabs.\n\nManage templates\n----------------\n\nFor template documents the application defines and owns, create\nthe template using a dedicated account representing the application.\n[Service accounts](/identity/protocols/application-default-credentials)\nare a good choice and avoid complications with Google Workspace policies that\nrestrict sharing.\n\nWhen you create instances of documents from templates, always use\nend-user credentials. This gives users full control over the\nresulting document and prevents scaling issues related to per-user\nlimits in Drive.\n\nTo create a template using a service account, perform the following steps with\nthe application credentials:\n\n1. Create a document using [documents.create](/workspace/docs/api/reference/rest/v1/documents/create) in the Docs API.\n2. Update the permissions to allow the document recipients to read it using [permissions.create](/workspace/drive/api/v3/reference/permissions/create) in the Drive API.\n3. Update the permissions to allow template authors to write to it using [permissions.create](/workspace/drive/api/v3/reference/permissions/create) in the Drive API.\n4. Edit the template as required.\n\nTo create an instance of the document, perform the following steps with the user\ncredentials:\n\n1. Create a copy of the template using [files.copy](/workspace/drive/v3/reference/files/copy) in the Drive API.\n2. Replace values using [documents.batchUpdate](/workspace/docs/api/reference/rest/v1/documents/batchUpdate) in the Docs API."]]