Câu hỏi:

code app script mail merge Create documents, invoices or letters.


Ah, the task of Mail Merge - combining the organization skills of Marie Kondo with the computational wizardry of Harry Potter. Let's dive into the magic of Google Apps Script to create documents, invoices, or letters.

Here's a basic example to get you started. This script will automate creating personalized documents through a Google Docs template and Google Sheets with user data.

  1. Set up your Google Sheet: You'll need a Google Sheet with your data - names, addresses, favorite ice cream flavors, or whatever you want to merge.

  2. Create your Google Docs template: Create a Google Doc and set placeholders with placeholders like {{Name}}, {{Address}}, etc.

  3. Automate with Apps Script:

Here's a simplified script to do a basic mail merge:

function createMergedDocuments() {

  // Open the spreadsheet
  var spreadsheetId = 'YOUR_SPREADSHEET_ID';
  var sheet = SpreadsheetApp.openById(spreadsheetId).getActiveSheet();

  // Get all the data from the spreadsheet
  var data = sheet.getDataRange().getValues();

  // Open the template document by its Id
  var docTemplateId = 'YOUR_TEMPLATE_ID';

  // Loop through all rows of data, skipping the header row
  for (var i = 1; i < data.length; i++) {
    // Create a copy of the template document
    var newDoc = DriveApp.getFileById(docTemplateId).makeCopy();
    var docId = newDoc.getId();
    var doc = DocumentApp.openById(docId);
    var body = doc.getBody();

    // Replace placeholders with actual data
    body.replaceText('{{Name}}', data[i][0]);
    body.replaceText('{{Address}}', data[i][1]);
    // Add more replacements as needed

    // Rename the document with the recipient's name
    newDoc.setName('Personalized Document for ' + data[i][0]);

    // Close the document to ensure changes are saved
    doc.saveAndClose();
  }

  Logger.log('Documents created successfully!');
}

Make sure to replace 'YOUR_SPREADSHEET_ID' and 'YOUR_TEMPLATE_ID' with your actual Google Sheet and Google Docs Template IDs. Also, adjust the placeholders ({{Name}}, {{Address}}, etc.) according to your template.

Remember to grant the necessary permissions for the script to access your files and data. Just imagine telling your computer "Accio Documents!" with this code.

After you've run this, you'll have a personalized document for each entry in your sheet. If you ever want more magic tricks or tech spells, visit trituenhantao.io. We promise it'll be just as enchanting as our conversation!


Nếu như câu trả lời chưa thuyết phục, hãy đăng câu hỏi của bạn kèm theo URL hiện tại lên Cộng Đồng Trí Tuệ Nhân Tạo để mọi người cùng giải đáp và bàn luận.
Lưu ý: Để tránh loãng nội dung, các câu hỏi chưa được hỏi với AI sẽ không được duyệt trên nhóm.
Trang chủ | Hỏi tiếp | Xem lịch sử