Created
October 17, 2019 21:13
-
-
Save Tofuhippo/ef92e19c53a4f98f5daa24b37b07f12b to your computer and use it in GitHub Desktop.
A couple of helper functions I always use when automating workflow processes from Google Sheets in GAS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get a sheet from a given spreadsheet by the ID of the sheet | |
function getSheetById(spreadsheet, sheetId) { | |
return spreadsheet.getSheets().filter(function(sheet) {return sheet.getSheetId() == sheetId})[0]; | |
} | |
// Lowers and strips whitespace of an array or string | |
function lowerNoSpace(object) { | |
var type = object.constructor.name; | |
switch (type) { | |
case "String": | |
return object.toLowerCase().replace(/\s/g, ''); | |
case "Array": | |
for (i in object) { | |
object[i] = lowerNoSpace(object[i]); | |
} | |
return object; | |
default: | |
return object; | |
} | |
} | |
// returns a 1d array of column labels in column 1 from given sheet | |
function getColNames(sheet) { | |
var numColumns = sheet.getLastColumn(); | |
return sheet.getRange(1, 1, 1, numColumns).getValues()[0]; //Object[][] is returned, we want just the first subarray/row | |
} | |
// gets row labels in row 1 from given sheet. | |
function getRowNames(sheet) { | |
var numRows = sheet.getLastRow(); | |
var firstCol2d = sheet.getRange(1, 1, numRows, 1).getValues(); | |
var rowNames = Array.prototype.concat.apply([], firstCol2d); | |
return rowNames; | |
} | |
// finds a spreadsheet column index by using the column name in the first row in specified sheet. Return 0 on fail | |
function getColIndexByName(sheet, colName) { | |
var firstRow = lowerNoSpace(getColNames(sheet)); | |
return firstRow.indexOf(lowerNoSpace(colName))+1; | |
} | |
// finds a spreadsheet row index by using the row name in the first column in specified sheet. Return 0 on fail | |
function getRowIndexByName(sheet, rowName) { | |
var firstCol = lowerNoSpace(getRowNames(sheet)); | |
return firstCol.indexOf(lowerNoSpace(rowName))+1; | |
} | |
// gets the data from a cell at rowNum, columnNum in specified sheet | |
function getCellByRowNumColNum(sheet, rowNum, colNum) { | |
return sheet.getRange(rowNum,colNum).getValue(); | |
} | |
// gets the data from a cell at rowName, columnName in specified sheet | |
function getCellByRowNameColName(sheet, rowName, colName) { | |
var row = getRowIndexByName(sheet, rowName); | |
var col = getColIndexByName(sheet, colName); | |
if (row==0 || col==0) { | |
return "A cell with those row and column labels does not exist"; | |
} | |
return getCellByRowNumColNum(sheet, row, col); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment