เราสามารถทำ mail merge ด้วย Google Sheet และ Docs ด้วยขั้นตอนง่ายๆ ดังนี้
ที่ Google Docs
- สร้าง folder เปล่าขึ้นมา 1 อัน สำหรับเก็บเอกสารที่จะใช้เป็น template
- สร้างไฟล์ Google Docs ใหม่ ให้มีเนื้อหาที่เราต้องการ
- ในส่วนที่จะดึงข้อมูลจาก Google Sheets มาให้ (ฟิวด์) ให้พิมพ์เป็นรูปแบบที่เป็นเอกลักษณ์ที่ไม่ซ้ำกับข้อความอื่นๆในเอกสารนั้นๆ โดยทั่วไปอาจจะใช้เป็น {{ F01 }} {{ F02 }} หรือจะตั้งชื่อให้สื่อความหมายกว่านี้ก็ได้ เช่น {{ FIRST_NAME }} {{ LAST_NAME }} เป็นต้น
- บันทึกไฟล์เก็บไว้
ที่ Google Sheet
- ให้สร้าง Sheet ใหม่ในโฟว์เดอร์เดียวกับที่เราสร้าง template จาก Google Docs
- ให้แถวแรกเป็นชื่อฟิวด์ และแถวต่อๆมาเป็นข้อมูล
- เลือกเมนู Extensions > Apps Script
-
ใส่ 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 } } - กดปุ่ม Run เอกสารที่เป็นรูปแบบ pdf จะถูกสร้างในโฟวเดอร์เดียวกับที่เราเก็บไฟล์ Sheet ไว้
หมายเหตุ
- การสร้างโฟวเดอร์ไม่จำเป็น แต่จะเป็นการสะดวกเพราะเอกสารต่างๆจะถูกบันทึกเก็บไว้ที่เดียวกันหมดไม่ปนกับเอกสารอื่น
- templateId ให้ดูจาก url ของ template ที่อยู่ระหว่างตัว /d/ กับ /edit ของเอกสารของเรา
- การรัน script อาจมีปัญหาเรื่องของ permission ให้เลือกรันแบบ unsafe เพราะมิฉะนั้นเราต้องส่ง script ของเรานี้เข้าไปรับการอนุมัติจาก Google ก่อนก็จะเป็นการยุ่งยากเสียเวลา หากเราต้องการใช้ mail merge เป็นการส่วนตัวเท่านั้น
Photo by Craig Adderley: pexels.com