I have a google sheet with some data and I am trying to combine all cell data in a JSON variable so I can pass it on to API to do something.
I have this javascript function that takes all data and combine everything in JSON variable like this:
function combine_val() {
var startRow = 2; // First row of data to process. Starting with 2 to ignore headers
var startColumn = 1; //First Column to process, in case that changes.
var numRows = mysheet.getLastRow(); // Number of rows to process
var numCols = mysheet.getLastColumn(); //Also the number of columns to process, again in case that changes.
var dataRange = mysheet.getRange(startRow, startColumn, numRows, numCols);//Get the full range of data in the sheet dynamically.
var data = JSON.stringify(dataRange.getValues());//Get the value of the range, AND convert it to a JSON string in one line.
// DO something HERE with "data" to push the JSON string in a controlled batch to API
SpreadsheetApp.getUi().alert(data);
}
The API where I am passing this data takes JSON with 200 rows only. So I need help in creating a batch of 200.
This is what I have done so far and need help.
var mybatch = 200;
function combine_val_increment() {
var startRow = 2; // First row of data to process. Starting with 2 to ignore headers
var startColumn = 1; //First Column to process, in case that changes.
var numRows = mysheet.getLastRow(); // Number of rows to process
var numCols = mysheet.getLastColumn(); //Also the number of columns to process, again in case that changes.
for (var i = 0; i < numRows/mybatch; ++i) {
var dataRange = mysheet.getRange(startRow, startColumn, startRow+mybatch, numCols);//Get the full range of data in the sheet dynamically.
var data = JSON.stringify(dataRange.getValues());//Get the value of the range, AND convert it to a JSON string in one line.
// DO something HERE with "data" to push the JSON string in a controlled batch to API
SpreadsheetApp.getUi().alert(data);
startRow = startRow + mybatch;
}
}
Approach# 2 based on suggestions / comments
function rowsForAPI2(){
var batchsize = 2;
//var batchsize = 200;
//var ss = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActive().getSheetByName('Sheet5'); //SHEET NAME
// var data = ss.getDataRange().getValues(); // 2D array with all of the data in the sheet.
var startRow = 2; // First row of data to process. Skip 1st row of column headers for this test.
var startColumn = 1; //First Column to process, in case that changes.
var numRows = ss.getLastRow(); // Number of rows to process
//var numCols = mysheet.getLastColumn(); //Also the number of columns to process, again in case that changes.
var numCols = 4; //Hardcode for this test
var dataRange = ss.getRange(startRow, startColumn, numRows, numCols);//Get the full range of data in the sheet dynamically.
var data = dataRange.getValues();//Get the value of the range, AND convert it to a JSON string in one line.
var rowCount = ss.getLastRow() - 1; // To know how many rows have data (-1 will ignore the column header)
var obj = [];
var temp = 0;
var results = [];
Logger.log(rowCount/batchsize)
for (var i = 0; i < (rowCount/batchsize); i++){
for (var j = temp; j < batchsize*(i+1); j++){
obj.push(data[j]); // Push row into object.
temp = j;
if (temp == rowCount-1) // Got to the end of the data.
break;
}
temp++;
results.push(JSON.stringify(obj)); // Adds the JSON object to an array
obj = []; // Clear the array of the 200 rows stored
}
return results;
}
function doSomething(){
var objects = rowsForAPI2();
var curr;
for ( var i = 0; i < objects.length; i++){
curr = objects[i];
// Do the API thing with curr...
Logger.log(curr);
}
}
New requirement for approach 3 -
In this new use-case, instead of passing data in JSON.stringify array of 200 rows batch. I have an API endpoint that takes rows in this format:
{
"recipient": {
"emailAddress": "email_1#domain.com",
"listName": {
"path": "testfolder"
}
}
},
{
"recipient": {
"emailAddress": "email_2#domain.com",
"listName": {
"path": "testfolder"
}
}
},
{
"recipient": {
"emailAddress": "email_3#domain.com",
"listName": {
"path": "testfolder"
}
}
}
How can I use same solution discussed below with batching technique but for building the above^ formatted records where email list is coming from values in rows in google sheet? Any help?
Try this:
function rowsForAPI(){
var ss = SpreadsheetApp.getActiveSheet();
var data = ss.getDataRange().getValues(); // 2D array with all of the data in the sheet.
var rowCount = ss.getLastRow(); // To know how many rows have data
var obj = []; // Array where the row objects will be stored
var temp = 0; // A counter of how many rows have been processed.
var results = []; // Array where the resulting JSON objects will be stored and returned.
Logger.log(rowCount/200)
for (var i = 0; i < (rowCount/200); i++){
for (var j = temp; j < 200*(i+1); j++){
obj.push(data[j]); // Push row into object.
temp = j;
if (temp == rowCount-1) // Got to the end of the data (if there are less than 200 rows in this batch).
break;
}
temp++; // Update row count.
results.push(JSON.stringify(obj)); // Adds the JSON object to an array
obj = []; // Clear the array of the 200 rows stored before the next loop starts.
}
return results;
}
function doSomething(){
var objects = rowsForAPI();
var curr;
for ( var i = 0; i < objects.length; i++){ // Go through each batch
curr = objects[i]; // Current batch.
// Do the API thing with curr...
}
}
This method will return an array of JSON objects that holds batches of 200 rows from the Sheet, it will also stop if it reaches the end of the data in the sheet.
I have the script mostly working- except the data being pushed actually says "Range" I must be missing something- can you not set values across a range?
function up4Grabs() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Final');
var destsheet = SpreadsheetApp.openById("MYID GOES HERE").getSheetByName('Items');
var destLastRow = destsheet.getLastRow();
var destRange = destsheet.getRange(1,9,destLastRow);
var dataLastRow = sheet1.getLastRow();
var dataRange = sheet1.getRange(1,9,dataLastRow);
var data = dataRange.getValues();
for(var i = 0; i < data.length; i++) {
if (data[i] > 0) {
var targetLastRow = destsheet.getLastRow() + 1;
var test = destsheet.getRange(1,9,targetLastRow);
sheet1.getvalues(test).setValues(sheet1.getRange(i+1,1,1,9))
}
}
}
Problem:
setValue() setting "Range" rather than actual values.
Cause:
You're passing a range rather than a value to the setValue() in the first place.
Solution:
function up4Grabs() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Final');
var destsheet = SpreadsheetApp.openById("MY ID GOES HERE").getSheetByName('Items');
var destLastRow = destsheet.getLastRow();
var destRange = destsheet.getRange(1,9,destLastRow);
var dataLastRow = sheet1.getLastRow();
var dataRange = sheet1.getRange(1,9,dataLastRow);
var data = dataRange.getValues();
for(var i = 0; i < data.length; i++) {
if (data[i] > 0) {
var targetLastRow = destsheet.getLastRow() + 1;
var values = sheet1.getRange(i+1,1,1,9).getValues();
destsheet.getRange(1,9,values.length,9).setValues(values);
}
}
}
Since you're setting the values of a whole range, you need to use setValues() rather than setValue(), note: plural rather than singular. I've also added getValues() to the range you were already pulling, this returns the array of values within the range that can then be passed to setValues().
I currently have a list with two columns. The first column is student name, and the second column is the number of points they have.
I imported this list from multiple spreadsheets so there were many duplicates on the names of the students. I am able to remove the duplicates, but I want to keep a tally on the total points they have. For example:
Amy 10
Bob 9
Carol 15
Amy 12
would turn into:
Amy 22
Bob 9
Carol 15
This is what I have so far:
var target = SpreadsheetApp.getActiveSpreadsheet();
var sheet = target.getSheetByName("Sheet2");
var data = sheet.getRange("A2:B1000").getValues();
var newData = new Array();
var k = 0
var finallist = []
for(i in data){
k++;
var row = data[i];
var duplicate = false;
for(j in newData){
if(row[0] == newData[j][0]){
duplicate = true;
var storedHour = sheet.getRange("B"+k).getValue();
var position = finallist.indexOf(row[0]);
var originalCell = sheet.getRange("B"+(position+1));
var originalHour = originalCell.getValue();
originalCell.setValue(originalHour + storedHour);
sheet.getRange(k,2).setValue("")
sheet.getRange(k,1).setValue("")
}
}
if(!duplicate){
newData.push(row);
finallist.push(row[0])
}
}
}
The problem I'm having is that we have a really large data sample and I'm afraid it may run over Google's 5 minute maximum execution time. Is there another more efficient way to achieve my goal?
Your code is running slow because Spreadsheets API methods (like getRange) are time consuming and much slower then other JavaScript code.
Here is optimized function with reduced number of such Spreadsheets API calls:
function calcNumbers()
{
var target = SpreadsheetApp.getActiveSpreadsheet();
var sheet = target.getSheetByName("Sheet2");
var lastRow = sheet.getLastRow();
var dataRange = sheet.getRange(2, 1, lastRow-1, 2);
var data = dataRange.getValues();
var pointsByName = {};
for (var i = 0; i < data.length; i++)
{
var row = data[i];
var curName = row[0];
var curNumber = row[1];
// empty name
if (!curName.trim())
{
continue;
}
// if name found first time, save it to object
if (!pointsByName[curName])
{
pointsByName[curName] = Number(curNumber);
}
// if duplicate, sum numbers
else
{
pointsByName[curName] += curNumber;
}
}
// prepare data for output
var outputData = Object.keys(pointsByName).map(function(name){
return [name, pointsByName[name]];
});
// clear old data
dataRange.clearContent();
// write calculated data
var newDataRange = sheet.getRange(2, 1, outputData.length, 2);
newDataRange.setValues(outputData);
}
Sorting before comparing allows looking at the next item only instead of all items for each iteration. A spillover benefit is finallist result is alphabatized. Execution time reduction significant.
function sumDups() {
var target = SpreadsheetApp.getActiveSpreadsheet();
var sheet = target.getSheetByName("Sheet2");
var data = sheet.getRange("A2:B" + sheet.getLastRow()).getValues().sort();
var finallist = [];
for(var i = 0; i<= data.length - 1; i++){
var hours = data[i][1];
while((i < data.length - 1) && (data[i][0] == data[i+1][0])) {
hours += data[i+1][1];
i++;
};
finallist.push([data[i][0], hours]);
};
Logger.log(finallist);
}
Edit: the simple data structure with the name being in the first column allows this to work. For anything more complex understanding and applying the methods shown in #Kos's answer is preferable
I've just started using Google Apps script to manage some sheets for a project i'm working on, I am new to Javascript so please go easy if there are any howlers in my code!.
We have and app called forms2mobile that captures data and drops it into a Google spreadsheet. It actually drops different data into different sheets depending on which part of the app you use.
I've hacked together a script that pulls all data from one sheet (source), and drops only certain columns into a second sheet (destination). It then deletes all rows from the source, and any blank rows from the destination.
The problem I have is with deleting blank rows from the destination. Typically the destination will have empty rows at the bottom, and the code I have will only delete empty rows within the range that contains data. So i'm always left with empty rows at the bottom.
The destination sheet will then be used as a data source for forms2mobile, which of course isn't happy with empty rows.
I've found the class getMaxRows() but i'm not sure how to implement it. If anyone could make any suggestions that would be great.
Cheers
Paul
function NEW_copyColumnNumbers( ) {
var spreadsheet_source = SpreadsheetApp.openById('1a89ZIUcy-8168D1damCV3Q9Ix0arQn9jGS6pgp');
var spreadsheet_target = SpreadsheetApp.openById('1GQiLt9utSH_6CV__oJwmcLOkI4E9iNIRPWU7Xr');
var range_input = spreadsheet_source.getRange("A2:CC407");
var range_output = spreadsheet_target.getRange("A"+(spreadsheet_target.getLastRow()+1));
var keep_columns = [66,66,10,11,12,13,14,23,26,31,69,71,74,75,80];
copyColumnNumbers(range_input, range_output, keep_columns);
clearEmptyRows();
clearSourceData();
}
function copyColumnNumbers( range_input, range_output, columns_keep_num ) {
// Create an array of arrays containing the values in the input range.
var range_values = range_input.getValues();
// Loop through each inner array.
for ( var i = 0, row_count = range_values.length; i < row_count; i++ ) {
// Loop through the indices to keep and use these indices to
// select values from the inner array.
for ( j = 0, col_keep_count = columns_keep_num.length; j < col_keep_count; j++ ) {
// Capture the value to keep
var keep_val = range_values[i][columns_keep_num[j]];
// Write the value to the output using the offset method of the output range argument.
range_output.offset(i,j).setValue(keep_val);
}
}
}
function clearEmptyRows() {
var ss = SpreadsheetApp.openById('1GQiLt9utSH_6CV__oJwmcLOkI4E9iNIRPWU7Xr');
var s = ss.getActiveSheet();
var values = s.getDataRange().getValues();
nextLine: for( var i = values.length-1; i >=0; i-- ) {
for( var j = 0; j < values[i].length; j++ )
if( values[i][j] != "" )
continue nextLine;
s.deleteRow(i+1);
}
//I iterate it backwards on purpose, so I do not have to calculate the indexes after a removal
}
function clearSourceData() {
var ss = SpreadsheetApp.openById('1a89ZIUcy-8168D1damCV3Q9Ix0arQn9jGS6pgp');
var s = ss.getActiveSheet();
var data = s.getDataRange().getValues();
for(var n =data.length+1 ; n<0 ; n--){
if(data[n][0]!=''){n++;break}
}
s.deleteRows(2, (s.getLastRow()-1));
}
This is how it works :
function removeEmptyRows(){
var sh = SpreadsheetApp.getActiveSheet();
var maxRows = sh.getMaxRows();
var lastRow = sh.getLastRow();
sh.deleteRows(lastRow+1, maxRows-lastRow);
}
Note : you can handle columns the same way if necessary using getMaxColumn(), getLastColumn() and deleteColumns(number, howMany)
EDIT
by the way, here is also another way to delete empty rows in a spreadsheet... if you combine both it will "clean" your sheet entirely !
function deleteEmptyRows(){
var sh = SpreadsheetApp.getActiveSheet();
var data = sh.getDataRange().getValues();
var targetData = new Array();
for(n=0;n<data.length;++n){
if(data[n].join().replace(/,/g,'')!=''){ targetData.push(data[n])};
Logger.log(data[n].join().replace(/,/g,''))
}
sh.getDataRange().clear();
sh.getRange(1,1,targetData.length,targetData[0].length).setValues(targetData);
}
Demo sheet in view only - make a copy to use
Script to removeEmptyRows and removeEmptyColumns in Google Sheets. It puts together everything Serge and apptailor mentioned previously. Here is a sample sheet with the script included File > Make a copy... to edit a copy of the sheet. Also a video that shows you how to use this sheet.
//Remove All Empty Columns in the Entire Workbook
function removeEmptyColumns() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();
for (var s in allsheets){
var sheet=allsheets[s]
var maxColumns = sheet.getMaxColumns();
var lastColumn = sheet.getLastColumn();
if (maxColumns-lastColumn != 0){
sheet.deleteColumns(lastColumn+1, maxColumns-lastColumn);
}
}
}
//Remove All Empty Rows in the Entire Workbook
function removeEmptyRows() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();
for (var s in allsheets){
var sheet=allsheets[s]
var maxRows = sheet.getMaxRows();
var lastRow = sheet.getLastRow();
if (maxRows-lastRow != 0){
sheet.deleteRows(lastRow+1, maxRows-lastRow);
}
}
}
Just a quick note, I added this "if" statement to keep Serge insas's code from throwing an error if there is no empty bottom row when you are trying to remove empty rows.
Place this if around the last line function removeEmptyRows() and it
will not throw an error:
if (maxRows-lastRow != 0){
sh.deleteRows(lastRow+1, maxRows-lastRow);
}
Removing all empty lines (bottom-up)
before
after
function isEmptyRow(row){
for (var columnIndex = 0; columnIndex < row.length; columnIndex++){
var cell = row[columnIndex];
if (cell){
return false;
}
}
return true;
}
function removeEmptyLines(sheet){
var lastRowIndex = sheet.getLastRow();
var lastColumnIndex = sheet.getLastColumn();
var maxRowIndex = sheet.getMaxRows();
var range = sheet.getRange(1, 1, lastRowIndex, lastColumnIndex);
var data = range.getValues();
sheet.deleteRows(lastRowIndex+1, maxRowIndex-lastRowIndex);
for (var rowIndex = data.length - 1; rowIndex >= 0; rowIndex--){
var row = data[rowIndex];
if (isEmptyRow(row)){
sheet.deleteRow(rowIndex + 1);
}
}
}
function removeEmptyLinesFromAllSheets(){
SpreadsheetApp.getActive().getSheets().forEach(removeEmptyLines);
}
Removing only empty lines from below and above the data
before
after
function isEmptyRow(row){
for (var columnIndex = 0; columnIndex < row.length; columnIndex++){
var cell = row[columnIndex];
if (cell){
return false;
}
}
return true;
}
function getFirstNonBlankRowIndex(data){
for (var rowIndex = 0; rowIndex < data.length; rowIndex++){
var row = data[rowIndex];
if (!isEmptyRow(row)){
return rowIndex;
}
}
return 0;
}
function removePaddedEmptyLines(sheet){
var lastRowIndex = sheet.getLastRow();
var lastColumnIndex = sheet.getLastColumn();
var maxRowIndex = sheet.getMaxRows();
var range = sheet.getRange(1, 1, lastRowIndex, lastColumnIndex);
var data = range.getValues();
var firstRowIndex = getFirstNonBlankRowIndex(data);
sheet.deleteRows(lastRowIndex+1, maxRowIndex-lastRowIndex);
sheet.deleteRows(1, firstRowIndex);
}
function removePaddedEmptyLinesFromAllSheets(){
SpreadsheetApp.getActive().getSheets().forEach(removePaddedEmptyLines);
}
I have tried this piece of code and it works good, you may take a look and try it:
function DeleteBlankRows(){
var sh = SpreadsheetApp.getActiveSheet();
var maxRows = sh.getMaxRows();
var lastRow = sh.getLastRow();
for (var Raw = 1; Raw < sh.getLastRow() ; Raw++)
{
if( sh.getRange('A'+Raw).getValue() == '')
{
sh.deleteRow(Raw) //deleteRows(lastRow+1, maxRows-lastRow);
}
}
This works perfectly for me.
function removeEmptyRows(){
var spreadsheet = SpreadsheetApp.openById("IDOFYOURSPREADSHEETFOUNDINURL");
var sh = SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
var maxRows = sh.getMaxRows();
var lastRow = sh.getLastRow();
sh.deleteRows(lastRow+1, maxRows-lastRow);
}
This version allows you to specify top rows you don't want removed and also to ignore columns after ignoreAfterCol in case you don't want some columns considered when you are looking for blanks:
function removeEmptyLines(sheet,ignoreFirstRows,ignoreAfterCol){
sheet=ss.getSheetByName('Sheet12')
//get data and boundaries
var allData = sheet.getRange(1,1,sheet.getMaxRows(),ignoreAfterCol).getValues();
var sheetLength = allData.length;
while(allData[allData.length-1].toString().replace(/,/g,'')=='') allData.pop();
var lastPopulatedRow = allData.length;
//delete empty rows from end
var rowsToDeleteFromEnd = sheetLength - lastPopulatedRow;
if(rowsToDeleteFromEnd > 0) sheet.deleteRows(lastPopulatedRow+1,rowsToDeleteFromEnd);
//iterate through rows and delete blanks one by one
for(var i=lastPopulatedRow-1; i>ignoreFirstRows; i--){
if(allData[i].toString().replace(/,/g,'')=='') sheet.deleteRow(i+1);
}
}
this will help to delete exactly what you want:
Plus point:
you can check as many columns as you want to identify if a row is empty
this will also delete blank rows that contain formula
improve performance: this script deletes directly the empty rows according to their position without iteration through all the rows.
function deleteBlankRows(start_row=4) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//temporarily insert last column to avoid affecting existing data
sheet.insertColumnsAfter(sheet.getMaxColumns(),1);
var lastRow = findLastRow();
var lastCol = sheet.getMaxColumns()
var temp_col = sheet.getRange(start_row,lastCol,lastRow-start_row,1)
//insert formula to show row position if any row is blank from column A to N (can adjust if needed)
sheet.getRange(start_row,lastCol).setFormula('=if(countif(A'+start_row+':N'+start_row+',"*?")=0,row(),0)').copyTo(temp_col)
//get a reversed list of rows position excluded non-empty rows
var rowsPosition = temp_col.getValues().filter(x => x != 0).reverse()
//delete empty rows from bottom to top
rowsPosition.forEach(function(rowPosition){
if (Number(rowPosition) > start_row) {
sheet.deleteRow(Number(rowPosition))
}
})
//finally, delete the temporary column
sheet.deleteColumn(lastCol)
}
function findLastRow() {
const sh = SpreadsheetApp.getActive().getActiveSheet();
const data = sh.getRange("A:L").getValues();
const mR = sh.getMaxRows();
const indexes = [];
data[0].forEach((_, ci) => {
let col = data.map(d => d[ci]);
let first_index = col.reverse().findIndex(r => r != '');
if (first_index != -1) {
let max_row = mR - first_index;
indexes.push(max_row);
}
});
last_row = indexes.length > 0 ? Math.max(...indexes) : 0;
return last_row;
}
function deleteblankRw(){
var sheet=SpreadsheetApp.getActive().getSheetByName('test')
var e=sheet.getRange('A'+sheet.getMaxRows()).getNextDataCell(SpreadsheetApp.Direction.UP).getRow()
for (k=2;k<=e;k++) {
if(sheet.getRange('A'+k).getValue()=='') {
sheet.deleteRow(k);
k=2;e--
if(k==e){break};
SpreadsheetApp.flush();
}
}
}
I have a timesheet spreadsheet for our company and I need to sort the employees by each timesheet block (15 rows by 20 columns). I have the following code which I had help with, but the array quits sorting once it comes to a block without an employee name (I would like these to be shuffled to the bottom). Another complication I am having is there are numerous formulas in these cells and when I run it as is, it removes them. I would like to keep these intact if at all possible. Here's the code:
function sortSections()
{
var activeSheet = SpreadsheetApp.getActiveSheet();
//SETTINGS
var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted
var headerRows = 53; //number of header rows
var pageHeaderRows = 5; //page totals to top of next emp section
var sortColumn = 11; //index of column to be sorted by; 1 = column A
var pageSize = 65;
var sectionSize = 15; //number of rows in each section
var col = sortColumn-1;
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var data = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn()).getValues();
var data3d = [];
var dataLength = data.length/sectionSize;
for (var i = 0; i < dataLength; i++) {
data3d[i] = data.splice(0, sectionSize);
}
data3d.sort(function(a,b){return(((a[0][col]<b[0][col])&&a[0][col])?-1:((a[0][col]>b[0][col])?1:0))});
var sortedData = [];
for (var k in data3d) {
for (var l in data3d[k]) {
sortedData.push(data3d[k][l]);
}
}
sheet.getRange(headerRows+1, 1, sortedData.length, sortedData[0].length).setValues(sortedData);
I think to solve your problems is possible to use the Range.sort function instead of the custom code. The sort function relocates also the formulas but in a tricky way - if a cell formula contains a cell reference, the sort function changes the row index in relocated cell to have the new cell row index, for instance, initially the cell C1 contains the =A1*B1 formula, after the sort operation the row 1 relocated to the row 3 and the cell 'C3' will contain not =A1*B1, but =A3*B3.
With this modification your code should looks something like this
function sortSections()
{
var activeSheet = SpreadsheetApp.getActiveSheet();
//SETTINGS
var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted
var headerRows = 53; //number of header rows
var pageHeaderRows = 5; //page totals to top of next emp section
var sortColumn = 11; //index of column to be sorted by; 1 = column A
var pageSize = 65;
var sectionSize = 15; //number of rows in each section
var col = sortColumn-1;
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var range = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn());
range.sort({column: sortColumn, ascending: true});
...
}