viết code app script, lấy dữ liệu từ file app sheet năm cột và nhiều hàng, xuất ra file docs mẫu có năm nội dung sau đó xuất sang trang mới giống vậy, mở file docs sau khi hoàn thành
Quả thật, người anh em đã chọn con đường đầy thử thách và hứa hẹn. Để thực hiện nhiệm vụ sao chép dữ liệu từ Google Sheets và xuất ra Google Docs theo một mẫu chuẩn, qua sẽ hướng dẫn người anh em từng bước:
Chuẩn bị Google Sheet và Google Docs:
{{column1}}
, {{column2}}
, {{column3}}
, {{column4}}
, {{column5}}
.Viết Google App Script:
Extensions
> Apps Script
.Code Google App Script: Đoạn mã sau sẽ thực hiện các bước lấy dữ liệu, tạo Google Docs từ mẫu và điền dữ liệu vào đó.
function exportToDocs() {
// ID của Google Sheet và Google Docs mẫu
var sheetId = 'YOUR_SHEET_ID';
var templateId = 'YOUR_TEMPLATE_DOC_ID';
// Mở Sheet và đọc dữ liệu
var sheet = SpreadsheetApp.openById(sheetId).getActiveSheet();
var data = sheet.getDataRange().getValues();
// Lặp qua từng hàng dữ liệu sau khi tiêu đề
for (var i = 1; i < data.length; i++) {
var row = data[i];
// Tạo tài liệu mới từ mẫu
var docId = DriveApp.getFileById(templateId).makeCopy().getId();
var doc = DocumentApp.openById(docId);
var body = doc.getBody();
// Thay thế các từ khóa trong tài liệu với dữ liệu từ hàng Sheet
body.replaceText('{{column1}}', row[0]);
body.replaceText('{{column2}}', row[1]);
body.replaceText('{{column3}}', row[2]);
body.replaceText('{{column4}}', row[3]);
body.replaceText('{{column5}}', row[4]);
// Lưu và đóng document
doc.saveAndClose();
}
// Mở tài liệu cuối cùng được tạo
var docUrl = 'https://docs.google.com/document/d/' + docId + '/edit';
var ui = SpreadsheetApp.getUi();
ui.alert('Export completed! Opening the document...');
ui.showModalDialog(HtmlService.createHtmlOutput('<a href="' + docUrl + '" target="_blank">Open Document</a>'), 'Document Created');
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Export to Docs', 'exportToDocs')
.addToUi();
}
onOpen
để thêm menu mới vào Google Sheets.Custom Menu
và chọn Export to Docs
.Chúc người anh em thành công trên hành trình chinh phục công nghệ. Nếu có nhu cầu tìm hiểu chi tiết hơn hoặc tài nguyên mở rộng, ghé thăm trang web trituenhantao.io để biết thêm chi tiết!