Restez organisé à l'aide des collections Enregistrez et classez les contenus selon vos préférences.
Ce guide explique comment utiliser l'API Google Docs pour effectuer une fusion de courriers.
Introduction
Une mise en page avec imbrication de données extrait les valeurs des lignes d'une feuille de calcul ou d'une autre source de données, puis les insère dans un document de modèle. Vous pouvez ainsi créer un seul document principal (le modèle) à partir duquel vous pouvez générer de nombreux documents similaires, chacun personnalisé avec les données fusionnées. Le résultat n'est pas nécessairement utilisé pour l'envoi de courriers ou de lettres types, mais peut servir à n'importe quel autre fin, comme la génération d'un lot de factures client.
La fusion de courriers existe depuis l'apparition des feuilles de calcul et des traitements de texte, et fait partie de nombreux processus métier aujourd'hui. La convention consiste à organiser les données en un enregistrement par ligne, les colonnes représentant les champs des données, comme indiqué dans le tableau suivant:
Nom
Adresse
Zone
1
UrbanPq
123 1st St.
Ouest
2
Pawxana
456 2nd St.
Sud
L'application exemple de cette page montre comment utiliser les API Google Docs, Sheets et Drive pour éliminer les détails de la fusion de courriers, ce qui protège les utilisateurs des problèmes d'implémentation. Pour en savoir plus sur cet exemple Python, consultez le dépôt GitHub de l'exemple.
Exemple d'application
Cet exemple d'application copie votre modèle principal, puis fusionne les variables de votre source de données désignée dans chacune des copies. Pour essayer cet exemple d'application, commencez par configurer votre modèle:
Notez l'ID du document du nouveau fichier. Pour en savoir plus, consultez ID de document.
Définissez la variable DOCS_FILE_ID sur l'ID du document.
Remplacez les coordonnées par des variables d'espace réservé de modèle que l'application fusionnera avec les données sélectionnées.
Voici un exemple de modèle de lettre avec des espaces réservés pouvant être fusionnés avec des données réelles provenant d'une source telle que du texte brut ou Sheets. Voici à quoi ressemble ce modèle:
Ensuite, choisissez le texte brut ou Sheets comme source de données à l'aide de la variable SOURCE. L'exemple utilise par défaut le texte brut, ce qui signifie que les données de l'exemple utilisent la variable TEXT_SOURCE_DATA. Pour extraire des données à partir de Sheets, remplacez la variable SOURCE par 'sheets' et faites-la pointer vers notre feuille d'exemple (ou la vôtre) en définissant la variable SHEETS_FILE_ID.
Voici à quoi ressemble la feuille pour que vous puissiez voir le format:
Essayez l'application avec nos exemples de données, puis adaptez-la à vos données et à votre cas d'utilisation. L'application de ligne de commande fonctionne comme suit:
Configuration
Récupérer les données de la source de données
Itérer chaque ligne de données
Créer une copie du modèle
Fusionner la copie avec les données
Lien de sortie vers le document nouvellement fusionné
Toutes les lettres nouvellement fusionnées s'affichent également dans Mon Drive de l'utilisateur. Voici un exemple de lettre fusionnée:
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)))
Pour en savoir plus, consultez le fichier README et le code source complet de l'application dans le dépôt GitHub de l'application exemple.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/03/22 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/03/22 (UTC)."],[],[],null,["This 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\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\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\nSource code \n\nPython \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- [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)"]]