Google Apps Scripting - Generic Headers in Spreadsheet - javascript

Quick look where I normally bother people tells me here is the new place to ask questions!
I have been making a script to create documentation generated from spreadsheet data which was in turn generated from a Google form. (Hope that makes sense...)
Anyway, I have been very successful with a lot of searching and bit of help but now I want to make my script homogeneous so I don't need to tinker with it when I want to setup new forms etc.
I have the getRowData function going from Googles script tutorials but instead of calling the row data from the normalised Headers i would like these to be generic i.e. Column1, Column2 etc.
I've pasted the tutorial function below, it passes the data to another function which normalizes the headers to use as objects, I was thinking thats where I could make them generic but I'm not sure how to get started on it...
Any help would be greatly appreciated!!
Thanks,
Alex
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
// Browser.msgBox(headers.toSource());
return getObjects(range.getValues(), normalizeHeaders(headers));
// return getObjects(range.getRowIndex);
}

If you want to get the columns using their index, why parse them to object at all? Just use the plain getValues!
var values = sheet.getDataRange().getValues();
var row2 = values[1];
var cell_in_col4 = row2[3];

It looks like you are missing "var" when declaring your columnHeadersRowIndex variable.

Related

Save multiple results of array values from getValues for recall later in google script (Apps Script)

I'm relatively new to scripting and I have spent hours getting myself to this point... so any help from here is much appreciated.
I am creating a sheets doc that calculates and generates quotes for a tradie friend of mine.
Each time He calculates a Quote on the Spreedsheet, I want to save all the data + recall it later.
On another occasion, he'll input new values into the cells & want to save all again, with a new quoteID and values, from the same spreadsheet.
Effectively, I need a saved copy of the values that can then be recalled by a particular ID later on if he wants to "regenerate" that quote..
Basically, I have an 3 arrays + 3 single cells that I want to get all values for (nailed this part)
// custom menu function
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Save Data','saveData')
.addToUi();
}
// function to save data
function saveData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var writesheet = ss.getSheetByName("Saved Quotes");
var houselabour = ss.getRange("Calculating the Quote!A7:B38").getValues();
Logger.log(houselabour);
var tradelabour = ss.getRange("Calculating the Quote!E7:F38").getValues();
var materials = ss.getRange("Calculating the Quote!H7:K38").getValues();
var quoteid = ss.getRange('Calculating the Quote!B2').getValue();
var surname = ss.getRange('Calculating the Quote!B1').getValue();
var datecreated = ss.getRange('Calculating the Quote!C2').getValue();
var s1 = houselabour.toString();
var s2 = tradelabour.toString();
var s3 = materials.toString();
writesheet.appendRow([quoteid,surname,datecreated,s1+s2+s3]);
}
//function to recall data
function recallData()
var ss = SpreadsheetApp.getActiveSpreadsheet();
var activequoteid = ss.getActiveCell("Customers").getValue();
//input values from saved data (by quoteid) into Calculating the Quote Spreadsheet... ???
Ideally, I would input these values (quoteid, surname, datecreated) into a new sheet (writesheet) and then i've made the array data into string so i can input it into a single cell (this cell doesn't need to be read, just re-called to fill in the original table later)
Later on, I want to recall the same values I originally extracted back into the original quote generator - "Calculating the Quote" sheet.
2 things: Is it possible, instead of converting the 3 arrays I have to strings, to just log them somewhere without necessarily displaying them in the sheet anywhere? It is essential that the code that runs on a dropdown menu selection "save data" saves the array data and then the next time it is run it does not overrride the original but saves as another
I have a few solutions in my head
1) name each result of the Save Data function something unique (saved as array)...
- i do not know how to do this!
- if i dont print it out anywhere, where does it go???
2) append a row on the save quotes spreadsheet with the string instead of array, then when recalling the data with a new function, convert the object from .getValues
- i also do not know how to do this
... I also feel like there's a super easy solution to this that i'm just completely missing.
Your help is much appreciated

Google Sheet Script Editor - setValues for array

I`m trying to replace old values with new values using setValues in Google sheet script.
The data is in the below link...
https://docs.google.com/spreadsheets/d/1pSUVkxM9FhSNgizedHbY2MnYGTnC2iiYLfrWsoPmDks/edit?usp=sharing
I`m basically trying to remove first 14 characters and the last 12 characters under "Tracker" column
Below is the code I tried..
function URLReplacement() {
var ss = SpreadsheetApp.getActive().getSheetByName("transformer");
var rng = ss.getRange("G:G");
var data = rng.getValues();
for (var items in data)
{
var newer = data[items][0].substring(14)
// Turn these strings into an array
var newerr = newer.split(" ")
// Turn this into 2 dimensional array to use setValues
ss.getRange("G:G").setValues([newerr])
Logger.log([newer]);
}
}
But now, I get errors with the setValues statement
Saying the range I set there do not match the data
What am I doing wrong here..?
Can anyone please provide me with suggestions / advice?
You want to convert from IMAGE_SUFFIX_"http://google.com"<xxxnouse>" to http://google.com at the column "G".
The format of IMAGE_SUFFIX_"http://google.com"<xxxnouse>" is constant.
If my understanding is correct, how about this modification? The reason of your error is that [newer] is not 2 dimensional array for using setValues(). If this error was removed, the header is removed by overwriting the empty value. So I would like to modify as follows.
Modification points:
When getLastRow() is used, the data size retrieved by it can be reduced from that retrieved by "G:G". By this, the process cost can be reduced.
Header is not retrieved by getRange(2, 7, ss.getLastRow(), 1).
From the format of IMAGE_SUFFIX_"http://google.com"<xxxnouse>", split() was used for parsing this value.
The converted data was put by setValues(). By this, the process cost can be also reduced.
Modified script:
function URLReplacement() {
var ss = SpreadsheetApp.getActive().getSheetByName("transformer");
var rng = ss.getRange(2, 7, ss.getLastRow(), 1); // Modified
var data = rng.getValues();
var convertedData = data.map(function(e) {return e[0] ? [e[0].split('"')[1]] : e}); // Added
rng.setValues(convertedData); // Added
}
Note:
In your shared sample Spreadsheet, the sheet name is "Sheet1". But your script uses "transformer" as the sheet name. Please be careful this.
If the format of actual values in your Spreadsheet is different from your shared Spreadsheet, this might not be able to be used.
References:
split()
setValues()
If this was not the result you want, I apologize.

getRange() with specific criteria in Google Apps Sheets Script

I'm very new to JavaScript, and have only recently started fiddling with coding.
I had found a question that is similar to what I'm asking, so I've tried to modify the suggestions to fit my needs, but am drawing a blank pulling together other resources to understand the solution.
That question and answer is here: range.getValues() With specific Date in Specific Cell
I hope to ask my question by adding it to that thread, but I'm unable to make a comment - only an Answer, as I have zero votes.
I want to know how I can use the range.setValues() function, but specify only rows of cells that fit a certain criteria (e.g. cell in column B = 1).
Mostly I understand the answer, I think - push the full list of data into another array, then use a for loop to identify which rows to "keep".
However, I don't understand a good chunk of the solution, specifically this portion:
data.forEach(function(row) {
var colHvalue = row[7];
var colKvalue = row[10];
if( /* your desired test */) {
// Add the name of the sheet as the row's 1st column value.
row.unshift(sheetName);
// Keep this row
kept.push(row);
}
});
where I'm confused:
What's function(row) refer to? It seems to me that "row" is not a defined variable, and is also not a method.
What are the objects being specified in the line var colHvalue = row[7];? And same for the second row.
How does the pushing and unshifting work?
Hope for some answers, thanks!
Edit:
So I still don't understand the detailed logic of the Answer to that other question, and wrote something else based off that:
function importtest() {
var sheetX = SpreadsheetApp.openById("XXX-XXX-XXX"); // workbook containing orginal data
var tabX = sheetX.getSheetByName("EXPORTER"); // tab containing original data
var rangeX = tabX.getRange(6,2,sheetX.getLastRow(),sheetX.getLastColumn()).getValues(); //range of full original data
var kept = [] ;
var data = rangeX ; //storing full data in "data"
// define function "latestrows", which fills up the "kept" array with selected rows
function latestrows() {
var datesent = data[i][2] ; // indicating dynamic cell position (using variable i) that determines if should be kept or not
var datarow = data[i] ; // specify the entire row of data
// loop statement; starting with i=0 (or row 1), and increasing until the last row of "data"
for ( i = 0; i < data.length ; i++) {
if (datesent == 1) { // if cell in the col indicating if it should be kept, is "1"
kept.push(datarow); //move the chosen rows of data into "kept"
}
}
}
var sheetX3 = SpreadsheetApp.openById("XXX-XX-XX"); // workbook import destination
var tabX3 = sheetX3.getSheetByName("IMPORTED"); // import destination tab
var rangeX3 = tabX3.getRange(7,3,kept.length,kept[0].length) // imported array range
rangeX3.setValues(kept); // set values
}
I get the error message TypeError: Cannot read property "length" from undefined. (line 31, file "Code"), which together with testing other modifications indicates to me that kept is empty. What am I missing?

How to use if then in google app scripts?

I'm working on an app that scans data into Google sheets. i have two sheets: sheet1 and sheet2. In sheet1 the data is entered into it after a scan is performed. But before the scan data can be entered, i would like to do an if function to check if there is a similar type of data in sheet2 before entering the data. if there isn't one then a message will be displayed such as "There is no such person in the database". I would also like to specify the column to check for similarity in sheet2 e.g A2:A100
Below is the script code
function doGet(e){
var ss = SpreadsheetApp.openByUrl("google sheet url");
//Give your Sheet name here
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function doPost(e){
var ss = SpreadsheetApp.openByUrl("google sheet url");
//Give your Sheet name here
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function insert(e,sheet){
// reciving scanned data from client i.e android app
var scannedData = e.parameter.sdata;
var d = new Date();
var ctime= d.toLocaleString();
sheet.appendRow([scannedData,ctime]);
return ContentService
.createTextOutput("Success")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
Thanks.
Google Apps Script is in essence JavaScript with different libraries. So your if statements are in essence all the same as there:
if (a1 == a2) {
a1 = 0
}
else if (a1 != a3) {
a1 = 1
}
else {
a1 = 'String'
}
Check on logic operators to find what you can do if you are unfamiliar with that and also read about the switch satement as it's also sometimes useful in place of if statements (not in your case, but might as well read up on it while you are on the topic).
EDIT:
As per your comment, to compare the data from specific columns it's quite simple and there are multiple ways of doing it. Think of it as a structure Spreadsheet → Sheet → Range → Value. So if you already have an object for the sheet you can do range = sheet1.getRange(1,1) which will get you the cell A1. Or you can use A1 notation for the getRange('A1'). If your range is a single cell you can then do range.getValue() which will return the value inside the cell.
Now you want to find if the data exists in another sheet, going 1 by 1 will not be effective as getValue() will bloat the script very quickly. Instead you might want to do vals = sheet2.getDataRange().getValues(). This will return a 2D array of all the values inside of the sheet. If you want to only check a specific column and you know you do not care about the rest you can just replace getDataRange() with something like .getRange(C:C) or the same would be getRange(1, 3, sheet2.getLastRow(), 1).
Then you will simply loop through the 2D array with vals[rowNum][colNum].
If the value is added manually to 1 cell and the script fires with an onEdit trigger, you can also get the value directly from the event object e where it's in onEdit(e).
Read up on getRange() (read those bellow as well) as well as getValue() (and getValues bellow that). Google has excellent documentation, just logically follow the structure for what you want to achieve.

indexOf returning -1 despite object being in the array - Javascript in Google Spreadsheet Scripts

I am writing a script for a Google Docs Spreadsheet to read a list of directors and add them to an array if they do not already appear within it.
However, I cannot seem to get indexOf to return anything other than -1 for elements that are contained within the array.
Can anyone tell me what I am doing wrong? Or point me to an easier way of doing this?
This is my script:
function readRows() {
var column = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("Director");
var values = column.getValues();
var numRows = column.getNumRows();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var directors = new Array();
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (directors.indexOf(row) == -1) {
directors.push(row);
} else {
directors.splice(directors.indexOf(row), 1, row);
}
}
for (var i = 2; i < directors.length; i++) {
var cell = sheet.getRange("F" + [i]);
cell.setValue(directors[i]);
}
};
When you retrieve values in Google Apps Script with getValues(), you will always be dealing with a 2D Javascript array (indexed by row then column), even if the range in question is one column wide. So in your particular case, and extending +RobG's example, your values array will actually look something like this:
[['fred'], ['sam'], ['sam'], ['fred']]
So you would need to change
var row = values[i];
to
var row = values[i][0];
As an aside, it might be worth noting that you can use a spreadsheet function native to Sheets to achieve this (typed directly into a spreadsheet cell):
=UNIQUE(Director)
This will update dynamically as the contents of the range named Director changes. That being said, there may well be a good reason that you wanted to use Google Apps Script for this.
It sounds like an issue with GAS and not the JS. I have always had trouble with getValues(). Even though the documentation says that it is a two dimensional array, you can't compare with it like you would expect to. Although if you use an indexing statement like values[0][1] you will get a basic data type. The solution (I hope there is a better way) is to force that object into a String() and then split() it back into an array that you can use.
Here is the code that I would use:
var column = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("Director");
var values = column.getValues();
values = String(values).split(",");
var myIndex = values.indexOf(myDirector);
If myDirector is in values you will get a number != -1. However, commas in your data will cause problems. And this will only work with 1D arrays.
In your case: var row = values[i]; row is an object and not the string that you want to compare. Convert all of your values to an array like I have above and your comparison operators should work. (try printing row to the console to see what it says: Logger.log(row))
I ran into a similar problem with a spreadsheet function that took a range as an object. In my case, I was wanting to do a simple search for a fixed set of values (in another array).
The problem is, your "column" variable doesn't contain a column -- it contains a 2D array. Therefore, each value is it's own row (itself an array).
I know I could accomplish the following example using the existing function in the spreadsheet, but this is a decent demo of dealing with the 2D array to search for a value:
function flatten(range) {
var results = [];
var row, column;
for(row = 0; row < range.length; row++) {
for(column = 0; column < range[row].length; column++) {
results.push(range[row][column]);
}
}
return results;
}
function getIndex(range, value) {
return flatten(range).indexOf(value);
}
So, since I wanted to simply search the entire range for the existance of a value, I just flattened it into a single array. If you really are dealing with 2D ranges, then this type of flattening and grabbing the index may not be very useful. In my case, I was looking through a column to find the intersection of two sets.
Because we are working with a 2D array, 2dArray.indexOf("Search Term") must have a whole 1D array as the search term. If we want to search for a single cell value within that array, we must specify which row we want to look in.
This means we use 2dArray[0].indexOf("Search Term") if our search term is not an array. Doing this specifies that we want to look in the first "row" in the array.
If we were looking at a 3x3 cell range and we wanted to search the third row we would use 2dArray[2].indexOf("Search Term")
The script below gets the current row in the spreadsheet and turns it into an array. It then uses the indexOf() method to search that row for "Search Term"
//This function puts the specified row into an array.
//var getRowAsArray = function(theRow)
function getRowAsArray()
{
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Get the current spreadsheet
var theSheet = ss.getActiveSheet(); // Get the current working sheet
var theRow = getCurrentRow(); // Get the row to be exported
var theLastColumn = theSheet.getLastColumn(); //Find the last column in the sheet.
var dataRange = theSheet.getRange(theRow, 1, 1, theLastColumn); //Select the range
var data = dataRange.getValues(); //Put the whole range into an array
Logger.log(data); //Put the data into the log for checking
Logger.log(data[0].indexOf("Search Term")); //2D array so it's necessary to specify which 1D array you want to search in.
//We are only working with one row so we specify the first array value,
//which contains all the data from our row
}
If someone comes across this post you may want to consider using the library below. It looks like it will work for me. I was getting '-1' return even when trying the examples provide (thanks for the suggestions!).
After adding the Array Lib (version 13), and using the find() function, I got the correct row!
This is the project key I used: MOHgh9lncF2UxY-NXF58v3eVJ5jnXUK_T
And the references:
https://sites.google.com/site/scriptsexamples/custom-methods/2d-arrays-library#TOC-Using
https://script.google.com/macros/library/d/MOHgh9lncF2UxY-NXF58v3eVJ5jnXUK_T/13
Hopefully this will help someone else also.
I had a similar issue. getValues() seems to be the issue. All other methods were giving me an indexOf = -1
I used the split method, and performed the indexOf on the new array created. It works!
var col_index = 1;
var indents_column = main_db.getRange(1,col_index,main_db.getLastRow(),1).getValues();
var values = String(indents_column).split(","); // flattening the getValues() result
var indent_row_in_main_db = values.indexOf(indent_to_edit) + 1; // this worked
I ran into the same thing when I was using
let foo = Sheet.getRange(firstRow, dataCol, maxRow).getValues();
as I was expecting foo to be a one dimensional array. On research for the cause of the apparently weird behavior of GAS I found this question and the explanation for the always two dimensional result. But I came up with a more simple solution to that, which works fine for me:
let foo = Sheet.getRange(firstRow, dataCol, maxRow).getValues().flat();

Categories

Resources