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.
Hướng dẫn này giải thích cách sử dụng API Google Tài liệu để hợp nhất thư.
Giới thiệu
Tính năng hợp nhất thư lấy các giá trị từ các hàng của một bảng tính hoặc một nguồn dữ liệu khác rồi chèn các giá trị đó vào một tài liệu mẫu. Điều này cho phép bạn tạo một tài liệu chính (mẫu) duy nhất để tạo nhiều tài liệu tương tự, mỗi tài liệu được tuỳ chỉnh bằng dữ liệu đang được hợp nhất. Kết quả không nhất thiết phải dùng cho thư hoặc thư mẫu, mà có thể dùng cho bất kỳ mục đích nào, chẳng hạn như tạo một lô hoá đơn cho khách hàng.
Tính năng hợp nhất thư đã xuất hiện từ khi có bảng tính và trình xử lý văn bản, đồng thời là một phần của nhiều quy trình công việc kinh doanh hiện nay. Quy ước là sắp xếp dữ liệu dưới dạng một bản ghi trên mỗi hàng, trong đó các cột đại diện cho các trường trong dữ liệu, như minh hoạ trong bảng sau:
Tên
Địa chỉ
Vùng
1
UrbanPq
123 đường 1st
Tây
2
Pawxana
456 2nd St.
Nam
Ứng dụng mẫu trên trang này cho thấy cách bạn có thể sử dụng các API Google Tài liệu, Trang tính và Drive để tóm tắt thông tin chi tiết về cách thực hiện tính năng hợp nhất thư, giúp người dùng không gặp phải vấn đề khi triển khai. Bạn có thể tìm thêm thông tin về mẫu Python này tại kho lưu trữ GitHub của mẫu.
Ứng dụng mẫu
Ứng dụng mẫu này sao chép mẫu chính của bạn, sau đó hợp nhất các biến từ nguồn dữ liệu được chỉ định vào từng bản sao. Để dùng thử ứng dụng mẫu này, trước tiên, hãy thiết lập mẫu:
Ghi lại mã tài liệu của tệp mới. Để biết thêm thông tin, hãy xem phần Mã nhận dạng tài liệu.
Đặt biến DOCS_FILE_ID thành mã tài liệu.
Thay thế thông tin liên hệ bằng các biến phần giữ chỗ mẫu mà ứng dụng sẽ hợp nhất với dữ liệu đã chọn.
Dưới đây là mẫu thư mẫu có phần giữ chỗ có thể hợp nhất với dữ liệu thực từ một nguồn như văn bản thuần tuý hoặc Trang tính. Mẫu đó sẽ có dạng như sau:
Tiếp theo, hãy chọn văn bản thuần tuý hoặc Trang tính làm nguồn dữ liệu bằng cách sử dụng biến SOURCE. Mẫu mặc định là văn bản thuần tuý, nghĩa là dữ liệu mẫu sử dụng biến TEXT_SOURCE_DATA. Để lấy dữ liệu từ Trang tính, hãy cập nhật biến SOURCE thành 'sheets' và trỏ biến đó đến trang tính mẫu của chúng ta (hoặc trang tính của riêng bạn) bằng cách đặt biến SHEETS_FILE_ID.
Dưới đây là giao diện của trang tính để bạn có thể xem định dạng:
Hãy dùng thử ứng dụng với dữ liệu mẫu của chúng tôi, sau đó điều chỉnh ứng dụng cho phù hợp với dữ liệu và trường hợp sử dụng của bạn. Ứng dụng dòng lệnh hoạt động như sau:
Thiết lập
Tìm nạp dữ liệu từ nguồn dữ liệu
Lặp lại qua từng hàng dữ liệu
Tạo bản sao của mẫu
Hợp nhất bản sao với dữ liệu
Đường liên kết đầu ra đến tài liệu mới hợp nhất
Tất cả thư mới hợp nhất cũng xuất hiện trong phần Drive của tôi của người dùng. Ví dụ về một thư đã hợp nhất sẽ có dạng như sau:
importtimeimportgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpError# Fill-in IDs of your Docs template & any Sheets data sourceDOCS_FILE_ID="195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE"SHEETS_FILE_ID="11pPEzi1vCMNbdpqaQx4N43rKmxvZlgEHE9GqpYoEsWw"# authorization constantsSCOPES=(# iterable or space-delimited string"https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/documents","https://www.googleapis.com/auth/spreadsheets.readonly",)# application constantsSOURCES=("text","sheets")SOURCE="text"# Choose one of the data SOURCESCOLUMNS=["to_name","to_title","to_company","to_address"]TEXT_SOURCE_DATA=(("Ms. Lara Brown","Googler","Google NYC","111 8th Ave\nNew York, NY 10011-5201",),("Mr. Jeff Erson","Googler","Google NYC","76 9th Ave\nNew York, NY 10011-4962",),)# fill-in your data to merge into document template variablesmerge={# sender data"my_name":"Ayme A. Coder","my_address":"1600 Amphitheatre Pkwy\nMountain View, CA 94043-1351","my_email":"http://google.com","my_phone":"+1-650-253-0000",# - - - - - - - - - - - - - - - - - - - - - - - - - -# recipient data (supplied by 'text' or 'sheets' data source)"to_name":None,"to_title":None,"to_company":None,"to_address":None,# - - - - - - - - - - - - - - - - - - - - - - - - - -"date":time.strftime("%Y %B %d"),# - - - - - - - - - - - - - - - - - - - - - - - - - -"body":("Google, headquartered in Mountain View, unveiled the new ""Android phone at the Consumer Electronics Show. CEO Sundar ""Pichai said in his keynote that users love their new phones."),}creds,_=google.auth.default()# pylint: disable=maybe-no-member# service endpoints to Google APIsDRIVE=build("drive","v2",credentials=creds)DOCS=build("docs","v1",credentials=creds)SHEETS=build("sheets","v4",credentials=creds)defget_data(source):"""Gets mail merge data from chosen data source."""try:ifsourcenotin{"sheets","text"}:raiseValueError(f"ERROR: unsupported source {source}; choose from {SOURCES}")returnSAFE_DISPATCH[source]()exceptHttpErroraserror:print(f"An error occurred: {error}")returnerrordef_get_text_data():"""(private) Returns plain text data; can alter to read from CSV file."""returnTEXT_SOURCE_DATAdef_get_sheets_data(service=SHEETS):"""(private) Returns data from Google Sheets source. It gets all rows of 'Sheet1' (the default Sheet in a new spreadsheet), but drops the first (header) row. Use any desired data range (in standard A1 notation). """return(service.spreadsheets().values().get(spreadsheetId=SHEETS_FILE_ID,range="Sheet1").execute().get("values")[1:])# skip header row# data source dispatch table [better alternative vs. eval()]SAFE_DISPATCH={k:globals().get(f"_get_{k}_data")forkinSOURCES}def_copy_template(tmpl_id,source,service):"""(private) Copies letter template document using Drive API then returns file ID of (new) copy. """try:body={"name":f"Merged form letter ({source})"}return(service.files().copy(body=body,fileId=tmpl_id,fields="id").execute().get("id"))exceptHttpErroraserror:print(f"An error occurred: {error}")returnerrordefmerge_template(tmpl_id,source,service):"""Copies template document and merges data into newly-minted copy then returns its file ID. """try:# copy template and set context data struct for merging template valuescopy_id=_copy_template(tmpl_id,source,service)context=merge.iteritems()ifhasattr({},"iteritems")elsemerge.items()# "search & replace" API requests for mail merge substitutionsreqs=[{"replaceAllText":{"containsText":{"text":"{{%s}}"%key.upper(),# {{VARS}} are uppercase"matchCase":True,},"replaceText":value,}}forkey,valueincontext]# send requests to Docs API to do actual mergeDOCS.documents().batchUpdate(body={"requests":reqs},documentId=copy_id,fields="").execute()returncopy_idexceptHttpErroraserror:print(f"An error occurred: {error}")returnerrorif__name__=="__main__":# get row data, then loop through & process each form letterdata=get_data(SOURCE)# get data from data sourcefori,rowinenumerate(data):merge.update(dict(zip(COLUMNS,row)))print("Merged letter %d: docs.google.com/document/d/%s/edit"%(i+1,merge_template(DOCS_FILE_ID,SOURCE,DRIVE)))
Để biết thêm thông tin, hãy xem tệp README và mã nguồn đầy đủ của ứng dụng tại kho lưu trữ GitHub của ứng dụng mẫu.
[[["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-03-22 UTC."],[],[],null,["# Mail merge with Docs API\n\nThis guide explains how to use the Google Docs API to perform a mail merge.\n| **Note:** If you want to perform a mail merge using the Gmail web UI, see [Send personalized emails with mail\n| merge](https://support.google.com/mail/answer/12921167).\n\nIntroduction\n------------\n\nA *mail merge* takes values from rows of a spreadsheet or another data source\nand inserts them into a template document. This lets you create a single primary\ndocument (the template) from which you can generate many similar documents, each\ncustomized with the data being merged. The result isn't necessarily used for\nmail or form letters, but can be for any purpose, such as generating a batch of\ncustomer invoices.\n\nMail merge has been around for as long as there have been spreadsheets and word\nprocessors, and is part of many business workflows today. The convention is to\norganize the data as one record per row, with the columns representing fields in\nthe data, as shown in the following table:\n\n| | Name | Address | Zone |\n|---|---------|-------------|-------|\n| 1 | UrbanPq | 123 1st St. | West |\n| 2 | Pawxana | 456 2nd St. | South |\n\nThe sample app on this page shows how you can use the Google Docs,\nSheets, and Drive APIs to abstract away the\ndetails of how mail merges are performed, protecting users from implementation\nconcerns. More information on this Python sample can be found at the sample's\n[GitHub\nrepo](https://github.com/googleworkspace/python-samples/tree/main/docs/mail-merge).\n| **Note:** You must have a Google Cloud project set up so that you have credentials to make this work. More information is available in the [Python\n| quickstart](/workspace/docs/api/quickstart/python). Be sure to have the Google Drive, Docs, and Sheets APIs enabled in your project and your credentials JSON file downloaded as `credentials.json`.\n\nSample application\n------------------\n\nThis sample app copies your primary template and then merges variables from your\ndesignated data source into each of the copies. To try this sample app, first\nset up your template:\n\n1. [Create a Docs file](/workspace/docs/api/how-tos/documents). Choose the template you want to use.\n2. Note the new file's document ID. For more information, see [Document\n ID](/workspace/docs/api/concepts/document#document-id).\n3. Set the `DOCS_FILE_ID` variable to the document ID.\n4. Replace the contact information with template placeholder variables that the app will merge with the selected data.\n\nHere's a [sample letter\ntemplate](https://drive.google.com/open?id=1Xycxuuv7OhEQUuzbt_Mw0TPMq02MseSD1vZdBJ3nLjk)\nwith placeholders that can be merged with real data from a source such as plain\ntext or Sheets. Here's what that template looks like:\n\n| The structure of the template variables is arbitrary. The example uses values enclosed in double braces `{{VALUE}}` because text like this is extremely unlikely to appear in document content. This style of variable placeholder naming is similar to what you'll find in most templating libraries.\n\nNext, choose either plain text or Sheets as your data source\nusing the `SOURCE` variable. The sample defaults to plain text, meaning the\nsample data uses the `TEXT_SOURCE_DATA` variable. To source data from\nSheets, update the `SOURCE` variable to `'sheets'` and point it\nto [our sample\nsheet](https://drive.google.com/open?id=18yqXLEMx6l__VAIN-Zo52pL18F3rXn0_-K6gZ-vwPcc)\n(or your own) by setting the `SHEETS_FILE_ID` variable.\n\nHere's what the sheet looks like so you can see the format:\n\nTry the app with our sample data, then adapt it to your data and use case. The\ncommand-line application works like this:\n\n- Setup\n- Fetch the data from the data source\n- Loop through each row of data\n - Create a copy of the template\n - Merge the copy with the data\n - Output link to newly-merged document\n\nAll newly merged letters also show up in the user's My Drive. An\nexample of a merged letter looks something like this:\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\n### Source code\n\n### Python\n\ndocs/mail-merge/docs_mail_merge.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/docs/mail-merge/docs_mail_merge.py) \n\n```python\nimport time\n\nimport google.auth\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n# Fill-in IDs of your Docs template & any Sheets data source\nDOCS_FILE_ID = \"195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE\"\nSHEETS_FILE_ID = \"11pPEzi1vCMNbdpqaQx4N43rKmxvZlgEHE9GqpYoEsWw\"\n\n# authorization constants\n\nSCOPES = ( # iterable or space-delimited string\n \"https://www.googleapis.com/auth/drive\",\n \"https://www.googleapis.com/auth/documents\",\n \"https://www.googleapis.com/auth/spreadsheets.readonly\",\n)\n\n# application constants\nSOURCES = (\"text\", \"sheets\")\nSOURCE = \"text\" # Choose one of the data SOURCES\nCOLUMNS = [\"to_name\", \"to_title\", \"to_company\", \"to_address\"]\nTEXT_SOURCE_DATA = (\n (\n \"Ms. Lara Brown\",\n \"Googler\",\n \"Google NYC\",\n \"111 8th Ave\\nNew York, NY 10011-5201\",\n ),\n (\n \"Mr. Jeff Erson\",\n \"Googler\",\n \"Google NYC\",\n \"76 9th Ave\\nNew York, NY 10011-4962\",\n ),\n)\n\n# fill-in your data to merge into document template variables\nmerge = {\n # sender data\n \"my_name\": \"Ayme A. Coder\",\n \"my_address\": \"1600 Amphitheatre Pkwy\\nMountain View, CA 94043-1351\",\n \"my_email\": \"http://google.com\",\n \"my_phone\": \"+1-650-253-0000\",\n # - - - - - - - - - - - - - - - - - - - - - - - - - -\n # recipient data (supplied by 'text' or 'sheets' data source)\n \"to_name\": None,\n \"to_title\": None,\n \"to_company\": None,\n \"to_address\": None,\n # - - - - - - - - - - - - - - - - - - - - - - - - - -\n \"date\": time.strftime(\"%Y %B %d\"),\n # - - - - - - - - - - - - - - - - - - - - - - - - - -\n \"body\": (\n \"Google, headquartered in Mountain View, unveiled the new \"\n \"Android phone at the Consumer Electronics Show. CEO Sundar \"\n \"Pichai said in his keynote that users love their new phones.\"\n ),\n}\n\ncreds, _ = google.auth.default()\n# pylint: disable=maybe-no-member\n\n# service endpoints to Google APIs\n\nDRIVE = build(\"drive\", \"v2\", credentials=creds)\nDOCS = build(\"docs\", \"v1\", credentials=creds)\nSHEETS = build(\"sheets\", \"v4\", credentials=creds)\n\n\ndef get_data(source):\n \"\"\"Gets mail merge data from chosen data source.\"\"\"\n try:\n if source not in {\"sheets\", \"text\"}:\n raise ValueError(\n f\"ERROR: unsupported source {source}; choose from {SOURCES}\"\n )\n return SAFE_DISPATCH[source]()\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n return error\n\n\ndef _get_text_data():\n \"\"\"(private) Returns plain text data; can alter to read from CSV file.\"\"\"\n return TEXT_SOURCE_DATA\n\n\ndef _get_sheets_data(service=SHEETS):\n \"\"\"(private) Returns data from Google Sheets source. It gets all rows of\n 'Sheet1' (the default Sheet in a new spreadsheet), but drops the first\n (header) row. Use any desired data range (in standard A1 notation).\n \"\"\"\n return (\n service.spreadsheets()\n .values()\n .get(spreadsheetId=SHEETS_FILE_ID, range=\"Sheet1\")\n .execute()\n .get(\"values\")[1:]\n )\n # skip header row\n\n\n# data source dispatch table [better alternative vs. eval()]\nSAFE_DISPATCH = {k: globals().get(f\"_get_{k}_data\") for k in SOURCES}\n\n\ndef _copy_template(tmpl_id, source, service):\n \"\"\"(private) Copies letter template document using Drive API then\n returns file ID of (new) copy.\n \"\"\"\n try:\n body = {\"name\": f\"Merged form letter ({source})\"}\n return (\n service.files()\n .copy(body=body, fileId=tmpl_id, fields=\"id\")\n .execute()\n .get(\"id\")\n )\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n return error\n\n\ndef merge_template(tmpl_id, source, service):\n \"\"\"Copies template document and merges data into newly-minted copy then\n returns its file ID.\n \"\"\"\n try:\n # copy template and set context data struct for merging template values\n copy_id = _copy_template(tmpl_id, source, service)\n context = merge.iteritems() if hasattr({}, \"iteritems\") else merge.items()\n\n # \"search & replace\" API requests for mail merge substitutions\n reqs = [\n {\n \"replaceAllText\": {\n \"containsText\": {\n \"text\": \"{{%s}}\" % key.upper(), # {{VARS}} are uppercase\n \"matchCase\": True,\n },\n \"replaceText\": value,\n }\n }\n for key, value in context\n ]\n\n # send requests to Docs API to do actual merge\n DOCS.documents().batchUpdate(\n body={\"requests\": reqs}, documentId=copy_id, fields=\"\"\n ).execute()\n return copy_id\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n return error\n\n\nif __name__ == \"__main__\":\n # get row data, then loop through & process each form letter\n data = get_data(SOURCE) # get data from data source\n for i, row in enumerate(data):\n merge.update(dict(zip(COLUMNS, row)))\n print(\n \"Merged letter %d: docs.google.com/document/d/%s/edit\"\n % (i + 1, merge_template(DOCS_FILE_ID, SOURCE, DRIVE))\n )\n```\n\nFor more information, see the `README` file and the full application source code\nat the sample app's [GitHub\nrepo](https://github.com/googleworkspace/python-samples/tree/main/docs/mail-merge).\n\nRelated topics\n--------------\n\n- [Send personalized emails with mail merge](https://support.google.com/mail/answer/12921167)\n- [Create a mail merge with Gmail \\& Google Sheets](/apps-script/samples/automations/mail-merge)"]]