tools, productivity

การทำ mail merge ด้วย Google Sheet และ Docs

เราสามารถทำ mail merge ด้วย Google Sheet และ Docs ด้วยขั้นตอนง่ายๆ ดังนี้
การทำ mail merge ด้วย Google Sheet และ Docs
Share this

เราสามารถทำ mail merge ด้วย Google Sheet และ Docs ด้วยขั้นตอนง่ายๆ ดังนี้

ที่ Google Docs

  1. สร้าง folder เปล่าขึ้นมา 1 อัน สำหรับเก็บเอกสารที่จะใช้เป็น template
  2. สร้างไฟล์ Google Docs ใหม่ ให้มีเนื้อหาที่เราต้องการ
  3. ในส่วนที่จะดึงข้อมูลจาก Google Sheets มาให้ (ฟิวด์) ให้พิมพ์เป็นรูปแบบที่เป็นเอกลักษณ์ที่ไม่ซ้ำกับข้อความอื่นๆในเอกสารนั้นๆ โดยทั่วไปอาจจะใช้เป็น {{ F01 }} {{ F02 }} หรือจะตั้งชื่อให้สื่อความหมายกว่านี้ก็ได้ เช่น {{ FIRST_NAME }} {{ LAST_NAME }} เป็นต้น
  4. บันทึกไฟล์เก็บไว้

ที่ Google Sheet

  1. ให้สร้าง Sheet ใหม่ในโฟว์เดอร์เดียวกับที่เราสร้าง template จาก Google Docs
  2. ให้แถวแรกเป็นชื่อฟิวด์ และแถวต่อๆมาเป็นข้อมูล
  3. เลือกเมนู Extensions > Apps Script
  4. ใส่ script นี้เข้าไป แล้วปรับแต่งค่าตามต้องการ

    function exportRowsToPDF() {
    const templateId = '171B92qV0TtAnB1HUiupz6MyeO1pv911nzVPHzM43Dpc'; // Replace with your template ID
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    const data = sheet.getDataRange().getValues();
    
    for (let i = 1; i < data.length; i++) { // Assuming the first row is headers
    // Make a copy of the template document using DriveApp
    const templateFile = DriveApp.getFileById(templateId);
    const docCopy = templateFile.makeCopy('Document for ' + data[i][0]); // Copying the template and renaming it
    const doc = DocumentApp.openById(docCopy.getId());
    const body = doc.getBody();
    
    // Replace placeholders in the document
    body.replaceText('{{F01}}', data[i][0]); // Change index as needed
    //
    body.replaceText('{{F02}}', data[i][1]); // Change index as needed
    //
    body.replaceText('{{F03}}', data[i][2]); // Change index as needed
    //
    body.replaceText('{{F04}}', data[i][3]); // Change index as needed
    // Add more replacements as needed
    
    doc.saveAndClose();
    
    // Export as PDF
    const pdfBlob = DriveApp.getFileById(doc.getId()).getAs('application/pdf');
    const pdfFile = DriveApp.createFile(pdfBlob);
    pdfFile.setName('Document for ' + data[i][0] + '.pdf'); // Naming the PDF file
    }
    }
    
  5. กดปุ่ม Run เอกสารที่เป็นรูปแบบ pdf จะถูกสร้างในโฟวเดอร์เดียวกับที่เราเก็บไฟล์ Sheet ไว้

หมายเหตุ

  • การสร้างโฟวเดอร์ไม่จำเป็น แต่จะเป็นการสะดวกเพราะเอกสารต่างๆจะถูกบันทึกเก็บไว้ที่เดียวกันหมดไม่ปนกับเอกสารอื่น
  • templateId ให้ดูจาก url ของ template ที่อยู่ระหว่างตัว /d/ กับ /edit ของเอกสารของเรา
  • การรัน script อาจมีปัญหาเรื่องของ permission ให้เลือกรันแบบ unsafe เพราะมิฉะนั้นเราต้องส่ง script ของเรานี้เข้าไปรับการอนุมัติจาก Google ก่อนก็จะเป็นการยุ่งยากเสียเวลา หากเราต้องการใช้ mail merge เป็นการส่วนตัวเท่านั้น

Photo by Craig Adderley: pexels.com

Post Views: 12