Google Apps Script: Tự Động Gửi Email, Tạo PDF Và Xử Lý Dữ Liệu Từ Google Sheets
Chia sẻ
"Hướng dẫn dùng Google Apps Script để tự động hóa: gửi email hàng loạt, tạo PDF từ template, đồng bộ Sheets với Forms, trigger tự động."
1. Apps Script: JavaScript Cho Google Workspace
Google Apps Script là nền tảng scripting chạy trên đám mây, dựa trên JavaScript. Nó tích hợp sâu với Gmail, Sheets, Docs, Drive, Calendar — cho phép tự động hóa mọi workflow. Không cần cài đặt, chạy trực tiếp trên server Google.
Use cases phổ biến: tự động gửi email hàng ngày, generate PDF từ template, sync data giữa sheets, tạo custom menu, web app đơn giản. Bài viết hướng dẫn 3 kỹ thuật quan trọng nhất.
2. Gửi Email Tự Động
function sendDailyReport() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Report");
const data = sheet.getDataRange().getValues();
// Build HTML email
let html = "Báo Cáo Hàng Ngày
";
data.forEach((row, i) => {
html += "" + row.map(cell =>
`<${i===0?"th":"td"}>${cell}${i===0?"th":"td"}>`
).join("") + " ";
});
html += "
";
GmailApp.sendEmail(
"manager@company.com",
"Báo Cáo Doanh Thu " + new Date().toLocaleDateString("vi-VN"),
"",
{ htmlBody: html }
);
}MailApp.sendEmail() giới hạn 100 email/ngày (free), GmailApp.sendEmail() giới hạn 500/ngày. Dùng GmailApp để có nhiều options hơn: htmlBody, attachments, cc, bcc.
3. Tạo PDF Từ Google Docs Template
function generateInvoice() {
const templateId = "1abc...xyz"; // Google Docs template ID
const folder = DriveApp.getFolderById("folder_id");
const data = SpreadsheetApp.getActive()
.getSheetByName("Invoices").getDataRange().getValues();
data.slice(1).forEach(row => {
const copy = DriveApp.getFileById(templateId)
.makeCopy(`Invoice_${row[0]}`, folder);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
body.replaceText("{{customer}}", row[1]);
body.replaceText("{{amount}}", row[2].toLocaleString() + " ₫");
body.replaceText("{{date}}", row[3]);
doc.saveAndClose();
// Convert to PDF
const pdf = copy.getAs("application/pdf");
folder.createFile(pdf).setName(`Invoice_${row[0]}.pdf`);
copy.setTrashed(true); // Remove Docs copy
});
}4. Triggers: Tự Động Chạy Theo Lịch
Triggers cho phép script chạy tự động: Time-driven (mỗi ngày/tuần/tháng), onEdit (khi edit cell), onFormSubmit (khi submit Google Form), onOpen (khi mở file). Set trigger: Edit → Current project triggers → Add Trigger.
// Programmatic trigger: chạy mỗi ngày 8h sáng
function createDailyTrigger() {
ScriptApp.newTrigger("sendDailyReport")
.timeBased()
.everyDays(1)
.atHour(8)
.create();
}5. Custom Menu Và Sidebar
Tạo menu riêng trong Google Sheets: onOpen function thêm menu items. Khi user click, chạy function tương ứng. Dùng HtmlService để tạo sidebar với UI tùy chỉnh — form nhập liệu, dashboard mini.
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("🔧 Tools")
.addItem("Gửi báo cáo", "sendDailyReport")
.addItem("Tạo hóa đơn PDF", "generateInvoice")
.addSeparator()
.addItem("Clean data", "cleanData")
.addToUi();
}6. Xử Lý Dữ Liệu Hàng Loạt
Apps Script xử lý nhanh hơn manual: getDataRange().getValues() load tất cả data vào array, xử lý trong memory, ghi ngược bằng setValues(). Tránh getRange/setValue trong loop — chậm như VBA không tối ưu.
7. Quotas Và Limitations
Free account: 6 phút/lần chạy, 90 phút/ngày, 100 email/ngày. Workspace: 30 phút/lần, 6 giờ/ngày, 1500 email/ngày. Vượt quota → script bị terminate. Tips: batch processing, pagination, chunk data để tránh timeout.
8. Kết Luận
Google Apps Script biến Google Workspace thành automation platform. Gửi email, tạo PDF, sync data, custom menu — tất cả miễn phí. Bắt đầu với MailApp.sendEmail(), sau đó mở rộng sang triggers và PDF generation. JavaScript cơ bản là đủ để bắt đầu.
Bình luận
Đăng nhập để tham gia bình luận
Đăng nhậpNhận bài viết mới nhất
Đăng ký để nhận thông báo khi có bài viết mới. Không spam, chỉ kiến thức chất lượng.
Bài viết liên quan
Khám phá thêm các bài viết cùng chủ đề

