Skip to content

Instantly share code, notes, and snippets.

@jargetz
Last active August 14, 2020 17:41
Show Gist options
  • Save jargetz/5b8025cf73c5aff248bfe0d01e9869ab to your computer and use it in GitHub Desktop.
Save jargetz/5b8025cf73c5aff248bfe0d01e9869ab to your computer and use it in GitHub Desktop.
Google Apps Script: Utility Functions 1) Match Columns by Name, 2) URL Obfuscate String
// Google Apps Script: Get Target File through Google Drive by ID, open as a spreadsheet.
/** Find a file in Google Drive by ID.
* fileID - fileID, which you can get from the ID section of the file URL
* return the file opened as a Spreadsheet
*/
function getSpreadsheetFromFileId(fileID) {
var file = DriveApp.getFileById(fileID);
if (!file) {
throw new Error("Critical file missing for script to work");
}
//You can replace this with a different app if you'd like.
return SpreadsheetApp.open(file);
}
// Google Apps Script: Look up a list of Column Headers in a Google Sheet and get a list back of their indices in the same order.
// I use this if I want to insert data into a different sheet and I don't want to hardcode column orderings
// or positions but instead find the columns dynamically. This assumes the column name remains the same.
/** Find the index of the column in a target sheet by matching name. Return
* an array of indices of each column.
* columnHeaders - an array of strings for the column headers you want to find, e.g. ["Name", "Date"]
* sheet - the google sheet (not spreadsheet)
* ignoreMissingColumns - if true place a -1 for missing columns, otherwise throw an error
* return a list of indices in the same order as the list of column names [2,1], Name was found in column 2, Date in column 1
*/
function matchColumnsByName(columnHeaders, sheet, ignoreMissingColumns) {
const columnHeadersIndices = [];
var data = sheet.getDataRange().getValues();
for (var p = 0; p < columnHeaders.length; p++) {
var colName = columnHeaders[p];
var col = data[0].indexOf(colName);
if (col != -1) {
columnHeadersIndices[p] = col
} else if(!ignoreMissingColumns) {
throw new Error("Unable to find column " + colName);
} else {
columnHeadersIndices[p] = -1;
}
}
return columnHeadersIndices;
}
//Google Apps Script - Custom Formula - URL Obfuscate:
// This function uses url encoding to obfuscate a string to pass through a URL param.
// This is in no way a secure way to protect data but does obfuscate strings that will likely show up in server logs.
function urlobfuscate (str) {
return str.split('').map(function(c) {
return '%' + c.charCodeAt(0).toString(16);
}).join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment