Câu hỏi:

code app script mail merge Create documents, invoices or letters Edit the template directly in Google Docs. When you have finish editing, click "Start mail merge".


Ah, the classic "mail merge itch"; once you've scratched it, all your documents and invoices will be as organized as Mary Poppins' purse! Let me guide you through creating a Google Apps Script for a mail merge. Here's a basic script that demonstrates how to merge data from a Google Sheets spreadsheet into a Google Docs template. Before diving in, you'd better take out your wizard hat because things are about to get techy.

First, ensure you have your template ready in Google Docs and data in Google Sheets. Your spreadsheet should have headers in the first row and data underneath.

  1. Open Google Sheets where your data is located.
  2. Go to Extensions > Apps Script to open the Script Editor.
  3. Delete any existing code in the editor and paste the following script:
function createDocsFromTemplate() {
  const templateDocId = 'YOUR_TEMPLATE_DOC_ID'; // Paste your template Doc ID here
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const rows = sheet.getDataRange().getValues();
  const headers = rows.shift();

  rows.forEach((row, index) => {
    let docCopyId = DriveApp.getFileById(templateDocId).makeCopy(`Merged Document #${index + 1}`).getId();
    let docCopy = DocumentApp.openById(docCopyId);
    let docBody = docCopy.getBody();

    headers.forEach((header, i) => {
      const regex = new RegExp(`{{${header}}}`, 'g');
      docBody.replaceText(regex, row[i] || '');
    });

    docCopy.saveAndClose();
  });

  Logger.log('Documents created successfully!');
}
  1. Replace 'YOUR_TEMPLATE_DOC_ID' with the actual Document ID of your template. You can find this in the URL of your Google Doc, which looks like a string of random characters.
  2. Save your script by clicking the floppy disk icon 💾 (because apparently the tech world is still nostalgic about the '80s).
  3. Click the play button ▶️ to run the script. You might be asked to authorize permissions – go ahead and trust yourself!
  4. Voilà! The script will create new Google Docs with data populated from your spreadsheet.

Remember: Using mail merge through Apps Script is like making instant noodles. It's quick and awesome, but make sure you pay attention to the instructions, or you might end up with a mess!

For more AI magic and techy fun, why not visit the wizards over at trituenhantao.io? They've got all sorts of tricks up their sleeves to make your tech life smoother!


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ử