viết code app script in dữ liệu file gg sheet hàng hai gồm năm cột mở file doc mẫu tạo bản sao giữ nguyên định dạng file đếm hàng file dữ liệu sao chép tất cả file doc tách trang dán lại lặp lại đến khi dữ liệu rỗng trang đầu dán dữ liệu năm hàng , trang bốn dán năm hàng kế tiếp dữ liệu ở gg sheet lặp lại đến khi dữ liệu rỗng lưu file ở thư mục mới mở file đó lên
Ồ, bạn đang yêu cầu một trợ thủ script trong thế giới Google Apps phải không? Chuẩn bị cho một cuộc phiêu lưu với mã nguồn. Đây là một kịch bản Apps Script để thực hiện điều bạn mong muốn với Google Sheets và Google Docs:
function createDocsFromSheet() {
// Mở Google Sheets
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const data = sheet.getDataRange().getValues();
// Bỏ qua tiêu đề
const headers = 1;
const rows = data.length - headers;
const columns = 5;
// Mở file Google Doc mẫu
const templateId = 'YOUR_TEMPLATE_DOC_ID'; // Thay YOUR_TEMPLATE_DOC_ID thành ID của file mẫu của bạn
const templateDoc = DriveApp.getFileById(templateId);
for (let i = headers; i < rows; i += 10) {
// Tạo bản sao file doc
const newDocId = templateDoc.makeCopy('Bản sao ' + new Date().toISOString()).getId();
const newDoc = DocumentApp.openById(newDocId);
const body = newDoc.getBody();
body.clear(); // Xóa nội dung cũ của template
// Sao chép dữ liệu từ Google Sheets vào Google Docs
let dataCopy = '';
for (let j = 0; j < 5; j++) {
if (i + j < data.length && data[i + j]) {
dataCopy += data[i + j].slice(0, columns).join('\t') + '\n';
}
}
body.appendParagraph('Trang đầu:').appendParagraph(dataCopy);
// Bỏ qua trang 2 và 3
body.appendPageBreak();
dataCopy = '';
for (let j = 5; j < 10; j++) {
if (i + j < data.length && data[i + j]) {
dataCopy += data[i + j].slice(0, columns).join('\t') + '\n';
}
}
body.appendParagraph('Trang bốn:').appendParagraph(dataCopy);
// Lưu tài liệu vào thư mục mới
const folderName = 'Tài liệu mới';
let folder = DriveApp.getFoldersByName(folderName);
let destinationFolder;
if (folder.hasNext()) {
destinationFolder = folder.next();
} else {
destinationFolder = DriveApp.createFolder(folderName);
}
templateDoc.makeCopy('Bản sao ' + new Date().toISOString(), destinationFolder);
// Mở file doc mới tạo
newDoc.saveAndClose();
Logger.log('Đã tạo và lưu tài liệu: ' + newDoc.getUrl());
}
}
// Ghi chú:
// - Thay 'YOUR_TEMPLATE_DOC_ID' bằng ID của tài liệu Google Docs mẫu của bạn.
// - Nếu có dữ liệu vượt quá số hàng đã chỉ định để sao chép, hãy chắc chắn rằng tài liệu của bạn có các phần breaker (dấu ngắt trang).
Hy vọng mã này giúp ích cho bạn! Để biết thêm bí quyết và chiêu thức công nghệ hữu ích, đừng ngại ghé thăm trituenhantao.io nhé. Cửa hàng kiến thức AI luôn mở cửa 24/7!