Câu hỏi:

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 đó:

  1. Mở tệp Google Sheet mà người anh em muốn xuất dữ liệu từ đó.
  2. Tạo một tệp mẫu (hoặc có thể dùng tệp hiện có) nơi dữ liệu sẽ được lưu trữ.
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:

  1. Thay SOURCE_SPREADSHEET_ID bằng id của Google Sheet nguồn (nơi sẽ lấy dữ liệu).
  2. Thay DESTINATION_SPREADSHEET_ID bằng id của Google Sheet đích (tệp mẫu).
  3. Tạo một function trong Google Apps Script và dán đoạn mã trên vào đó.
  4. Chạy function 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!


Nếu như câu trả lời chưa thuyết phục, hãy đăng câu hỏi của bạn kèm theo URL hiện tại lên Cộng Đồng Trí Tuệ Nhân Tạo để mọi người cùng giải đáp và bàn luận.
Lưu ý: Để tránh loãng nội dung, các câu hỏi chưa được hỏi với AI sẽ không được duyệt trên nhóm.
Trang chủ | Hỏi tiếp | Xem lịch sử