Write application script code to export google sheet file data with 4 columns and many rows to sample file in cell A5 in sheet 3 then save and open the file
Người anh em, qua hiểu nhu cầu của người anh em là muốn xuất dữ liệu từ Google Sheets với các cột từ một tệp Google Sheets hiện có và lưu vào một tệp mẫu khác tại ô A5 trong sheet thứ ba. Qua xin chỉ dẫn từng bước chi tiết bằng cách sử dụng Google Apps Script để đạt được mục tiêu này.
Dưới đây là mã mẫu để thực hiện điều đó:
function exportData() {
// Tên của file Google Sheet cần xuất dữ liệu từ đó
var sourceSpreadsheetId = 'SOURCE_SPREADSHEET_ID';
var sourceSheetName = 'Sheet1'; // Tên của sheet có dữ liệu cần xuất
// Tên file Google Sheet nơi dữ liệu sẽ được lưu (tệp mẫu)
var destinationSpreadsheetId = 'DESTINATION_SPREADSHEET_ID';
var destinationSheetName = 'Sheet3'; // Tên của sheet nơi dữ liệu sẽ được lưu
// Mở tệp Google Sheet cần xuất dữ liệu từ đó
var sourceSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetId);
var sourceSheet = sourceSpreadsheet.getSheetByName(sourceSheetName);
// Lấy dữ liệu từ 4 cột đầu tiên, bắt đầu từ hàng thứ 2 (bỏ qua hàng tiêu đề)
var range = sourceSheet.getRange(2, 1, sourceSheet.getLastRow()-1, 4);
var data = range.getValues();
// Mở tệp mẫu
var destinationSpreadsheet = SpreadsheetApp.openById(destinationSpreadsheetId);
var destinationSheet = destinationSpreadsheet.getSheetByName(destinationSheetName);
// Chèn dữ liệu vào ô A5 của sheet 3 của tệp mẫu
var destinationRange = destinationSheet.getRange(5, 1, data.length, data[0].length);
destinationRange.setValues(data);
// Lưu các thay đổi (Apps Script sẽ tự động lưu các thay đổi)
// Mở tệp mẫu
var url = destinationSpreadsheet.getUrl();
var htmlOutput = HtmlService.createHtmlOutput('<a href="' + url + '" target="_blank">Click here to open the file</a>');
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Open File');
}
Người anh em cần làm những điều sau để script hoạt động đúng:
SOURCE_SPREADSHEET_ID
bằng id của Google Sheet nguồn (nơi sẽ lấy dữ liệu).DESTINATION_SPREADSHEET_ID
bằng id của Google Sheet đích (tệp mẫu).exportData
từ trình soạn thảo Google Apps Script.Nếu người anh em gặp sự cố hoặc cần thêm trợ giúp, đừng quên ghé thăm trituenhantao.io để tìm thêm thông tin hữu ích!