Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Một ứng dụng hữu ích của Google Docs API là hợp nhất thông tin từ một hoặc nhiều nguồn dữ liệu vào một tài liệu.
Trang này trình bày cách bạn có thể lấy dữ liệu từ một nguồn bên ngoài và chèn dữ liệu đó vào một tài liệu mẫu hiện có.
Mẫu là một loại tài liệu đặc biệt chứa cùng một văn bản cố định cho tất cả tài liệu được tạo từ mẫu, cùng với các phần giữ chỗ được chỉ định nơi có thể đặt văn bản động khác. Ví dụ: một mẫu hợp đồng có thể có nội dung cố định, cùng với các vị trí cho tên, địa chỉ và các thông tin khác của người nhận. Sau đó, ứng dụng của bạn có thể hợp nhất dữ liệu dành riêng cho khách hàng vào mẫu để tạo tài liệu hoàn chỉnh.
Cách tiếp cận này hữu ích vì một số lý do sau:
Nhà thiết kế có thể dễ dàng tinh chỉnh thiết kế của tài liệu bằng trình chỉnh sửa Google Tài liệu. Cách này dễ dàng hơn nhiều so với việc điều chỉnh các tham số trong ứng dụng để đặt bố cục được kết xuất.
Tách nội dung khỏi bản trình bày là một nguyên tắc thiết kế nổi tiếng với nhiều lợi ích.
Công thức cơ bản
Sau đây là ví dụ về cách bạn có thể sử dụng Docs API để hợp nhất dữ liệu vào một tài liệu:
Tạo tài liệu bằng nội dung giữ chỗ để hỗ trợ bạn thiết kế và định dạng. Mọi định dạng văn bản bạn muốn thay thế sẽ được giữ nguyên.
Đối với mỗi phần tử mà bạn sẽ chèn, hãy thay thế nội dung phần giữ chỗ bằng một thẻ. Hãy nhớ sử dụng những chuỗi không có khả năng xuất hiện một cách bình thường. Ví dụ: {{account-holder-name}} có thể là một thẻ phù hợp.
Trong mã của bạn, hãy sử dụng Google Drive API để tạo bản sao của tài liệu.
Hãy xem xét ví dụ sau đây, trong đó thay thế 2 trường trên tất cả các thẻ của một mẫu bằng các giá trị thực để tạo ra một tài liệu hoàn chỉnh.
Để thực hiện thao tác hợp nhất này, bạn có thể dùng mã bên dưới.
Java
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()
Quản lý mẫu
Đối với các tài liệu mẫu mà ứng dụng xác định và sở hữu, hãy tạo mẫu bằng cách sử dụng một tài khoản chuyên biệt đại diện cho ứng dụng.
Tài khoản dịch vụ là một lựa chọn phù hợp và tránh được các vấn đề phức tạp liên quan đến chính sách của Google Workspace về việc hạn chế chia sẻ.
Khi tạo các bản sao của tài liệu từ mẫu, hãy luôn sử dụng thông tin đăng nhập của người dùng cuối. Điều này giúp người dùng có toàn quyền kiểm soát tài liệu kết quả và ngăn chặn các vấn đề về việc mở rộng quy mô liên quan đến giới hạn cho mỗi người dùng trong Drive.
Để tạo một mẫu bằng tài khoản dịch vụ, hãy thực hiện các bước sau bằng thông tin đăng nhập ứng dụng:
Tạo tài liệu bằng cách sử dụng documents.create trong API Tài liệu.
Cập nhật quyền để cho phép người nhận tài liệu đọc tài liệu đó bằng cách sử dụng permissions.create trong Drive API.
Cập nhật quyền để cho phép tác giả mẫu ghi vào đó bằng cách sử dụng permissions.create trong Drive API.
Chỉnh sửa mẫu theo yêu cầu.
Để tạo một phiên bản của tài liệu, hãy thực hiện các bước sau bằng thông tin đăng nhập của người dùng:
Tạo bản sao của mẫu bằng cách sử dụng files.copy trong Drive API.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 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."]]