Hợp nhất thư

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 trong 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 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 duy nhất (mẫu) mà từ đó bạn có thể tạo nhiều tài liệu tương tự, mỗi tài liệu được tuỳ chỉnh với dữ liệu đang được hợp nhất. Kết quả này không nhất thiết được sử dụng cho việc gửi thư hoặc thư biểu mẫu, nhưng có thể dùng cho bất kỳ mục đích nào, chẳng hạn như tạo một loạt hoá đơn của khách hàng.

Tính năng hợp nhất thư đã ra mắt từ lâu chúng ta đã có bảng tính và trình xử lý văn bản. Tính năng này đã trở thành một phần trong nhiều quy trình làm việc của doanh nghiệp 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 Address (Địa chỉ) Vùng
1 UrbanPq 123 Đường 1 Tây
2 Chó Pawxana 456 Đường số 2 Nam

Ứng dụng mẫu trên trang này cho bạn biết cách sử dụng 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 việc hợp nhất thư, giúp bảo vệ người dùng khỏi những lo ngại liên quan đến việc triển khai. Bạn có thể xem 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, 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 của bạn:

  1. Tạo tệp Tài liệu. Chọn mẫu bạn muốn sử dụng.
  2. 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ã tài liệu.
  3. Đặt biến DOCS_FILE_ID thành mã nhận dạng tài liệu.
  4. 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 chữ cái, trong đó 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ẽ trô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 sẽ là văn bản thuần tuý, nghĩa là dữ liệu mẫu sẽ sử dụng biến TEXT_SOURCE_DATA. Để lấy nguồn dữ liệu trên Trang tính, hãy cập nhật biến SOURCE thành 'sheets' và trỏ biến đó vào trang tính mẫu của chúng tôi (hoặc trang tính của 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 bằng dữ liệu mẫu của chúng tôi, sau đó điều chỉnh 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 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ả các chữ cái mới hợp nhất cũng xuất hiện trong thư mục Drive của tôi của người dùng. Ví dụ về một chữ cái hợp nhất sẽ có dạng như sau:

Mã nguồn

Python

docs/mail-merge/docs_mail_merge.py
import time

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Fill-in IDs of your Docs template & any Sheets data source
DOCS_FILE_ID = "195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE"
SHEETS_FILE_ID = "11pPEzi1vCMNbdpqaQx4N43rKmxvZlgEHE9GqpYoEsWw"

# authorization constants

SCOPES = (  # 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 constants
SOURCES = ("text", "sheets")
SOURCE = "text"  # Choose one of the data SOURCES
COLUMNS = ["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 variables
merge = {
    # 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 APIs

DRIVE = build("drive", "v2", credentials=creds)
DOCS = build("docs", "v1", credentials=creds)
SHEETS = build("sheets", "v4", credentials=creds)


def get_data(source):
  """Gets mail merge data from chosen data source."""
  try:
    if source not in {"sheets", "text"}:
      raise ValueError(
          f"ERROR: unsupported source {source}; choose from {SOURCES}"
      )
    return SAFE_DISPATCH[source]()
  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


def _get_text_data():
  """(private) Returns plain text data; can alter to read from CSV file."""
  return TEXT_SOURCE_DATA


def _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") for k in SOURCES}


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")
    )
  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


def merge_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 values
    copy_id = _copy_template(tmpl_id, source, service)
    context = merge.iteritems() if hasattr({}, "iteritems") else merge.items()

    # "search & replace" API requests for mail merge substitutions
    reqs = [
        {
            "replaceAllText": {
                "containsText": {
                    "text": "{{%s}}" % key.upper(),  # {{VARS}} are uppercase
                    "matchCase": True,
                },
                "replaceText": value,
            }
        }
        for key, value in context
    ]

    # send requests to Docs API to do actual merge
    DOCS.documents().batchUpdate(
        body={"requests": reqs}, documentId=copy_id, fields=""
    ).execute()
    return copy_id
  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


if __name__ == "__main__":
  # get row data, then loop through & process each form letter
  data = get_data(SOURCE)  # get data from data source
  for i, row in enumerate(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 ứng dụng đầy đủ tại kho lưu trữ GitHub của ứng dụng mẫu.