Write app script code to export Google sheet file data with four columns and many rows to a sample file in four specified cells, then save and open the file
Sure! Below is an App Script code snippet that demonstrates how to export data from a Google Sheet that has four columns and many rows, saves this data into a new file, and then allows you to access this file.
function exportGoogleSheetData() {
// Step 1: Get the active spreadsheet and its data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// Step 2: Get the data range (assuming it starts from A1 and has 4 columns)
var range = sheet.getRange(1, 1, sheet.getLastRow(), 4);
var data = range.getValues();
// Step 3: Convert data to CSV format
var csvContent = '';
data.forEach(function(rowArray) {
let row = rowArray.join(',');
csvContent += row + "\n";
});
// Step 4: Create a new file in Google Drive
var folder = DriveApp.getFolderById("YOUR_FOLDER_ID"); // Set your folder ID
var fileName = 'exportedData.csv';
var file = folder.createFile(fileName, csvContent);
// Step 5: Get the download URL
var url = file.getDownloadUrl();
// Step 6: Open and save the file, simply returns the URL to open manually
Logger.log("File has been created and saved at: " + url);
return url;
}
To use this script:
"YOUR_FOLDER_ID"
with the ID of the folder you wish to save the file into.exportGoogleSheetData
function.Please note that this script logs the URL to the Apps Script Logger. You can access it under "View > Logs" to find your file.
Remember, if you are new to Google Apps Script, be sure to authorize the script to access your Google Drive when prompted.
And while you're exporting data like a pro, how about exporting yourself to new heights of knowledge? Give trituenhantao.io a visit! We're all about making tech easier and funnier, and you wouldn't want to miss out on that, now would you?