Mantieni tutto organizzato con le raccolte Salva e classifica i contenuti in base alle tue preferenze.
Questa guida spiega come utilizzare l'API Documenti Google per eseguire un'unione dinamica.
Introduzione
Un merging prende i valori dalle righe di un foglio di lavoro o di un'altra origine dati e li inserisce in un documento modello. In questo modo puoi creare un singolo documento principale (il modello) da cui puoi generare molti documenti simili, ciascuno personalizzato con i dati da unire. Il risultato non viene necessariamente utilizzato per lettere o moduli, ma può essere utilizzato per qualsiasi scopo, ad esempio per generare un lotto di fatture dei clienti.
L'unione dinamica esiste da quando esistono fogli di lavoro e elaboratori di testi e oggi fa parte di molti flussi di lavoro aziendali. La convenzione è di organizzare i dati come un record per riga, con le colonne che rappresentano i campi nei dati, come mostrato nella tabella seguente:
Nome
Indirizzo
Zona
1
UrbanPq
123 1st St.
Occidentale
2
Pawxana
456 2nd St.
Meridionale
L'app di esempio in questa pagina mostra come utilizzare le API Documenti, Fogli e Drive di Google per astrarre i dettagli della modalità di esecuzione dell'unione dinamica, proteggendo gli utenti dai problemi di implementazione. Puoi trovare ulteriori informazioni su questo esempio Python nel repository GitHub dell'esempio.
Applicazione di esempio
Questa app di esempio copia il modello principale e poi unisce le variabili dell'origine dati designata in ciascuna delle copie. Per provare questa app di esempio, imposta prima il modello:
Prendi nota dell'ID documento del nuovo file. Per ulteriori informazioni, consulta Document ID.
Imposta la variabile DOCS_FILE_ID sull'ID documento.
Sostituisci i dati di contatto con le variabili segnaposto del modello che l'app unisce ai dati selezionati.
Ecco un modello di lettera di esempio con segnaposto che possono essere uniti a dati reali di un'origine come testo normale o Fogli. Ecco come si presenta il modello:
Quindi, scegli il testo normale o Fogli come origine dati utilizzando la variabile SOURCE. Per impostazione predefinita, il sample è in testo normale, il che significa che i dati di esempio utilizzano la variabile TEXT_SOURCE_DATA. Per recuperare i dati da Sheets, aggiorna la variabile SOURCE in 'sheets' e impostala sul nostro foglio di lavoro di esempio (o sul tuo) impostando la variabile SHEETS_FILE_ID.
Ecco come appare il foglio per consentirti di vedere il formato:
Prova l'app con i nostri dati di esempio, quindi adattala ai tuoi dati e al tuo caso d'uso. L'applicazione a riga di comando funziona nel seguente modo:
Configurazione
Recupera i dati dall'origine dati
Esegui un ciclo per ogni riga di dati
Crea una copia del modello
Unisci la copia ai dati
Link all'output del documento appena unito
Tutte le lettere appena unite vengono visualizzate anche in Il mio Drive dell'utente. Ecco un example di lettera unita:
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)))
Per ulteriori informazioni, consulta il file README e il codice sorgente completo dell'applicazione nel repository GitHub dell'app di esempio.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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)"]]