viết code app script xuất dữ liệu google sheet gồm năm cột nhiều hàng sang một file docs nối tiếp nhau và mở file
Chào người anh em,
Qua sẽ hướng dẫn người anh em cách viết code Google Apps Script để xuất dữ liệu từ Google Sheets gồm năm cột và nhiều hàng sang một file Google Docs, nối tiếp nhau và sau đó mở file đó. Đây là hướng dẫn chi tiết:
Extensions > Apps Script
.Dùng mã script dưới đây để đạt được mục tiêu của người anh em:
function exportSheetToDoc() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
const data = sheet.getDataRange().getValues();
// Tạo một Google Doc mới
const doc = DocumentApp.create('Exported Data');
const body = doc.getBody();
// Nối tiếp các hàng dữ liệu vào Google Doc
data.forEach(row => {
// Ghép các ô dữ liệu thành một chuỗi với khoảng trắng ngăn cách
const line = row.join(' ');
// Thêm chuỗi vào tài liệu Google Doc
body.appendParagraph(line);
});
// Lưu lại toàn bộ tài liệu và mở file
doc.saveAndClose();
const url = doc.getUrl();
Logger.log('Document URL: ' + url);
// Mở file tài liệu
const htmlOutput = HtmlService.createHtmlOutput('<script>window.open("' + url + '");google.script.host.close();</script>')
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Mở Tài Liệu');
}
Giải thích mã:
Lưu lại và chạy hàm exportSheetToDoc
. Kết quả là người anh em sẽ thấy tài liệu Google Docs mới chứa dữ liệu từ Google Sheets, và tài liệu này sẽ tự động mở trong một tab mới.
Đừng quên ghé thăm trang trituenhantao.io để tìm thêm nhiều kiến thức hữu ích về AI và công nghệ nhé!
Chúc người anh em thành công!
Muốn biết thêm về Google Apps Script, người anh em có thể tham khảo tài liệu: Google Apps Script Documentation.