Compare text from url in Google web app script - google-apps-script

I have a container bound script which sends the query result perfectly.
function doGet(e) {
var ss = SpreadsheetApp.getActive();
var fn = e.parameter.FN;
var key = e.parameter.KEY;
if ( fn == 'CSA' ) {
var sh = ss.getSheetByName("SubmittedAnswers");
var data_raw = e.parameter.DATA.toString().replace("\n ", String.fromCharCode(10));
var data = data_raw.split('|||| ');
sh.appendRow(data);
return ContentService.createTextOutput("New record created");
}
else if ( fn == 'QQ' ) {
var sh = ss.getSheetByName("QuestionBank");
var rg = sh.getDataRange().getValues();
var rgq = sh.getName() + "!" + sh.getDataRange().getA1Notation();
var sql = "Select A, B, C, D, E, F WHERE G IS NOT NULL";
var qry = '=query(' + rgq + ';\"' + sql + '\";1)';
var ts = ss.insertSheet();
var setQuery = ts.getRange(1,1).setFormula(qry);
var getResult = ts.getDataRange().getValues();
ss.deleteSheet(ts);
return ContentService.createTextOutput(JSON.stringify(getResult));
}
}
Now i'm trying to add something like a password so that without this none can run the script. I've tried the code below.
else if ( fn == 'QQ' ) {
var sheet_key = ss.getSheetByName("DashBoard").getRange(9,2).getValue;
if (sheet_key == key) {
var sh = ss.getSheetByName("QuestionBank");
var rg = sh.getDataRange().getValues();
var rgq = sh.getName() + "!" + sh.getDataRange().getA1Notation();
var sql = "Select A, B, C, D, E, F WHERE G IS NOT NULL";
var qry = '=query(' + rgq + ';\"' + sql + '\";1)';
var ts = ss.insertSheet();
var setQuery = ts.getRange(1,1).setFormula(qry);
var getResult = ts.getDataRange().getValues();
ss.deleteSheet(ts);
return ContentService.createTextOutput(JSON.stringify(getResult));
}
}
The sheet_key is perfectly in the "DashBoard" sheet at cell (9,2). Still the script is not returning anything. If i remove the IF part the script works fine :(
What should I do?

This var sheet_key = ss.getSheetByName("DashBoard").getRange(9, 2).getValue;
needs to be this: var sheet_key = ss.getSheetByName("DashBoard").getRange(9, 2).getValue();
This is something that is easy to do with the current editor

Related

how to combine two if conditions in google sheets script to select cell value

I have a product sheet with product code in column A, price in sterling in column C and price in euro in column D. On the quotation sheet when I enter the product code in column A and enter currency in column c, I require the code to get the price value from the appropriate currency column in the products sheet. The code I have wrote is getting the price value from the products sheet okay but I am unable to get the code to select the correct price value based on currency. Can anyone please assist? Thanks
function updateData(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var quotationsSheet = ss.getSheetByName('QUOTATION');
var productSheet = ss.getSheetByName("PRODUCTS");
var lastProd = productSheet.getLastRow();
var priceList = productSheet.getRange(2,1,lastProd,4).getValues();
var drg = quotationsSheet.getRange(2, 1, quotationsSheet.getLastRow() - 1, 4);
var newPrice = quotationsSheet.getLastRow();
quotationsSheet.getRange(newPrice,2).setValue("Not found");
var code = quotationsSheet.getRange(newPrice,1).getValue();
var vs = drg.getValues();
vs.forEach((r,j) => {
let currency = r[2];
for (j = 0;j <priceList.length;j++){
if (priceList[j][0] == code && currency !='STERLING' ){
var description = priceList[j][1];
var price = priceList[j][2];
if (priceList[j][0] == code && currency !='EURO' )
var description = priceList[j][1];
var price = priceList[j][3];
quotationsSheet.getRange(newPrice,12).setValue(description)
quotationsSheet.getRange(newPrice,13).setValue(price)
}
}
});}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var quotationsSheet = ss.getSheetByName('QUOTATION');
var productsSheet = ss.getSheetByName("PRODUCTS");
var lastprod = productsSheet.getLastRow();
var productList = productsSheet.getRange(2,1,lastprod,4).getValues();
var currencyType = quotationsSheet.getLastRow();
var ct = quotationsSheet.getRange(currencyType,3,1,4);
var gs = ct.getValue();
var ge = ct.getValue();
var newProd = quotationsSheet.getLastRow();
quotationsSheet.getRange(newProd,2).setValue("Not found");
var code = quotationsSheet.getRange(newProd,1).getValue();
for (j = 0;j <productList.length;j++){
//for (i = 0;i <gs.length;i++)
if (productList[j][0] == code && gs == 'STERLING'){
var description = productList[j][1];
var price = productList[j][2];
quotationsSheet.getRange(newProd,6).setValue(description)
quotationsSheet.getRange(newProd,7).setValue(price)
} }
for (j = 0;j <productList.length;j++)
if (productList[j][0] == code && ge == 'EURO'){
var description = productList[j][1];
var price = productList[j][3];
quotationsSheet.getRange(newProd,6).setValue(description)
quotationsSheet.getRange(newProd,7).setValue(price)
}
}```

How to Include more sheets to write incremental number

I am using this function which works upon submitting the entry via Google Forms. Currently the below script is adding increment number to the Sheet1 Last empty row
I want to include two more sheets where same incremental number will be added to last empty row.
Column will be same where increment number is pasting that is Column A but Sheet1 data starts from Row2 and Sheet2 and Sheet3 Data starts from row6.
Your help will be much appreciated.
function uPDATEiT() {
var aiColumnName = 'A'; //Sheet1,Sheet2,Sheet3 same column
var requieredColName = 'C' //it is just for Sheet1
var ss = SpreadsheetApp.getActiveSpreadsheet()
var worksheet = ss.getSheetByName('Sheet1','Sheet2','Sheet3')
var aiColRange = worksheet.getRange(aiColumnName + '1:' + aiColumnName + '1000');
var aiCol = aiColRange.getValues();
var aiColIndex = aiColRange.getColumn();
var reqCol = worksheet.getRange(requieredColName + '1:' + requieredColName + '1000').getValues();
var maxSeq = 0;
for (var i = 0; i <= aiCol.length; i++) {
if (parseInt(aiCol[i], 10) > maxSeq) { maxSeq = aiCol[i]; }
}
for (var i = 0; i <= aiCol.length; i++) {
if (('' + reqCol[i]).length > 0 && ('' + aiCol[i]).length === 0) {
maxSeq++;
worksheet.getRange(i + 1, aiColIndex).setValue(maxSeq);
}
}
}
You can use this formula in Sheet2!A4 and Sheet3!A4:
={"ID's";ARRAYFORMULA(IF(B5:B<>"",vlookup(B5:B,{'Data Sheet (Sheet1)'!$B$2:$B,'Data Sheet (Sheet1)'!$A$2:$A},2,false),""))}
What it does?
Check if column B is not empty, then get the id from Sheet1 based on the matched name(column B) as a key in the vlookup()
Output:
Original Sheet2:
Sheet 2 using the formula:
Update
If you just want to append your maxSeq in Sheet2, you can use this:
Code:
function uPDATEiT() {
var aiColumnName = 'A'; //Sheet1,Sheet2,Sheet3 same column
var requieredColName = 'C' //it is just for Sheet1
var ss = SpreadsheetApp.getActiveSpreadsheet()
var worksheet = ss.getSheetByName('Data Sheet (Sheet1)')
var sheet2 = ss.getSheetByName('Sheet2')
Logger.log(worksheet)
Logger.log(sheet2.getLastRow())
var aiColRange = worksheet.getRange(aiColumnName + '1:' + aiColumnName + '1000');
var aiCol = aiColRange.getValues();
var aiColIndex = aiColRange.getColumn();
var reqCol = worksheet.getRange(requieredColName + '1:' + requieredColName + '1000').getValues();
var maxSeq = 0;
for (var i = 0; i <= aiCol.length; i++) {
if (parseInt(aiCol[i], 10) > maxSeq) { maxSeq = aiCol[i]; }
}
for (var i = 0; i <= aiCol.length; i++) {
if (('' + reqCol[i]).length > 0 && ('' + aiCol[i]).length === 0) {
maxSeq++;
worksheet.getRange(i + 1, aiColIndex).setValue(maxSeq);
sheet2.getRange(sheet2.getLastRow()+1,aiColIndex).setValue(maxSeq);
}
}
}
Get the last row in the sheet that contains data using getLastRow() , then increment it by 1.
Output:

Want to add Email sent function incase my temps are more than 8 appsscript

I have a code that I use to log temperatures into Google sheets..Code written in Appsscript. In this code, i want to add a function in the case 'temperature' that can send mail in case the incoming temperature to be logged is more than 8.. How can I do that? Someone help in that kind of code?
function doGet(e) {
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = '1hKXZEIx160TwXi5yUztGBDijNaGgAOjKWSmY-Mowo9M'; // Spreadsheet ID
//var sheetActive = SpreadsheetApp.openById("ID");
//var sheet = sheetActive.getSheetByName("Name");
var sheetActive = SpreadsheetApp.openById(sheet_id);
var sheet = sheetActive.getSheetByName("Theatre");
//var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet().getSheetByName("Sheet3");
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Africa/Nairobi", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
// if(){
// }
break;
// case 'humidity':
// rowData[3] = value; // Humidity in column D
// result += ' ,Humidity Written on column D';
// break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
Email Sent if value greater than 8
function doGet(e) {
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = '1hKXZEIx160TwXi5yUztGBDijNaGgAOjKWSmY-Mowo9M'; // Spreadsheet ID
//var sheetActive = SpreadsheetApp.openById("ID");
//var sheet = sheetActive.getSheetByName("Name");
var sheetActive = SpreadsheetApp.openById(sheet_id);
var sheet = sheetActive.getSheetByName("Theatre");
//var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet().getSheetByName("Sheet3");
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Africa/Nairobi", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
Logger.log(
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
Logger.log(`Date: ${new Date()} Value:${value}`);//Please add this
if(parseInt(value) > 8){
GmailApp.sendEmail('recipient emal','Subject',"message");
}
break;
// case 'humidity':
// rowData[3] = value; // Humidity in column D
// result += ' ,Humidity Written on column D';
// break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
GmailApp.sendEmail()

JDBC Connection from MySQL database to Spreadsheet very slow

I have created this script to push the data from my MySQL database to google spreadsheet.
Now, to be updated, I have created a trigger every 5 minutes to run the script, but strangely when I see the executions of the trigger, it run approximately every 40 minutes.
The run of the script is approximately 2 minutes and so after this it push the data in the spreadsheet.
Is there something wrong with the script?
And how can I enforce the update duration that I have established in the trigger?
var MAXROWS = 100000
var SEEKWELL_J_SHORT_DATES = { day: "yyyy-MM-dd", month: "yyyy-MM", year: "yyyy", dayNum: "dd", monthNum: "MM", yearNum: "yyyy", week: "W" }
var SEEKWELL_J_TIMEZONE = "UTC"
var HOST = 'xxx'
var PORT = 'xxx'
var USERNAME = 'xxx'
var PASSWORD = 'xxx'
var DATABASE = 'xxx'
var DB_TYPE = 'mysql'
function runSql(query, options) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
//var sheet = doc.getActiveSheet();
var sheet = doc.getSheets()[0];
var sheetName = sheet.getName();
//var cell = doc.getActiveSheet().getActiveCell();
var cell = sheet.getRange('a1');
var activeCellRow = cell.getRow();
var activeCellCol = cell.getColumn();
try {
var fullConnectionString = 'jdbc:' + DB_TYPE + '://' + HOST + ':' + PORT
var conn = Jdbc.getConnection(fullConnectionString, USERNAME, PASSWORD);
console.log('query :', query)
var stmt = conn.createStatement();
stmt.execute('USE ' + DATABASE);
var start = new Date();
var stmt = conn.createStatement();
stmt.setMaxRows(MAXROWS);
var rs = stmt.executeQuery(query);
} catch (e) {
console.log(e, e.lineNumber);
Browser.msgBox(e);
return false
}
var results = [];
cols = rs.getMetaData();
console.log("cols", cols)
var colNames = [];
var colTypes = {};
for (i = 1; i <= cols.getColumnCount(); i++) {
var colName = cols.getColumnLabel(i)
colTypes[colName] = { type: cols.getColumnTypeName(i), loc: i }
colNames.push(colName);
}
var rowCount = 1;
results.push(colNames);
while (rs.next()) {
curRow = rs.getMetaData();
rowData = [];
for (i = 1; i <= curRow.getColumnCount(); i++) {
rowData.push(rs.getString(i));
}
results.push(rowData);
rowCount++;
}
rs.close();
stmt.close();
conn.close();
console.log('results', results)
var colCount = results[0].length
var rowCount = results.length
var comment = "Updated on: " + (new Date()) + "\n" + "Query:\n" + query
if (options.omitColumnNames) {
results = results.slice(1)
rowCount -= 1
}
if (options.clearColumns && sheet.getLastRow() > 0) {
var startCellRange = sheet.getRange(startCell)
sheet.getRange(startCellRange.getRow(), startCellRange.getColumn(), sheet.getLastRow(), colCount).clearContent();
}
if (options.clearSheet) {
var startCellRange = sheet.getRange(startCell)
sheet.clear({ contentsOnly: true });
}
//sheet.getRange(activeCellRow, activeCellCol, rowCount, colCount).clearContent();
sheet.getRange(activeCellRow, activeCellCol, rowCount, colCount).setValues(results);
var cell = sheet.getRange(activeCellRow, activeCellCol)
cell.clearNote()
cell.setNote(comment);
sheet.setActiveRange(sheet.getRange(activeCellRow + rowCount + 1, activeCellCol))
console.log('query success!, rows = ', rowCount - 1)
}
function runSqlFromSheet() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sql = doc.getRange('query!A1').getDisplayValue();
var options = {}
Logger.log('sql;', sql)
runSql(sql, options)
}

Confirm that a value is in a spreadsheet column using Google Apps Script

This function sends email reminders based on a few conditions. One of the things I need to check for is that the Visit ID (which is in column 11 in the "email log" sheet) exists in a separate sheet ("DATA", stored in the enrollmentData variable). How do I search this array and return the ID to match in the IF statement below?
function sendReminders() {
var ss = SpreadsheetApp.getActiveSpreadsheet ();
var sheet = ss.getSheetByName("Email Log");
var rows = sheet.getLastRow()-1;
var startRow = 2; // First row of data to process
var numRows = rows; // Number of rows to process
var now = new Date();
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, 22)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var today = Utilities.formatDate(new Date(), "GMT-5", "m/d/yyyy")
var reminderSent = "Reminder Sent";
//get email body and subject
var bodyTem = ss.getSheetByName("Email Templates").getRange('b8').getValues();
var subject = ss.getSheetByName("Email Templates").getRange('d13').getValues();
//get enrollments data to search for visit ID
var enrollmentData = ss.getSheetByName("DATA").getRange('H:H').getValues();
for (var i = 0; i < data.length; i++) {
var row = data[i];
//set conditions
var sendReminder = row[18];
var reminderDate = row[19];
var reminderStatus = row[20];
var visitID = row[11]
//need condition to look for visit ID to not include already cancelled. Search enrollmentData for visitID and return as foundID for conditional below
if (sendReminder == "Yes" && reminderStatus != reminderSent && reminderDate >= today && visitID == foundID) {
//assemble email
var studentEmail = row[13];
var firstName = row[12];
var instructor = row[0];
var body1 = bodyTem.replace(/*name*/gi,firstName);
var body2 = body1.replace(/*instructorFull*/gi,instructor);
MailApp.sendEmail(studentEmail, subject, body2);
//need to write in that the reminder email was sent.
sheet.getRange(startRow + i, 20).setValue(reminderSent);
sheet.getRange(startRow + i, 21).setValue(now);
};
};
};
You want to search the array
var enrollmentData = ss.getSheetByName("DATA").getRange('H:H').getValues();
The method getValues always returns a double array: in this case, it's of the form [[1], [2], [3],..] since each row has one element. I usually flatten this:
var enrollmentDataFlat = enrollmentData.map(function(row) {return row[0];});
Now enrollmentDataFlat is like [1, 2, 3, ..] so indexOf will work as usual:
if (enrollmentDataFlat.indexOf(visitID) != -1) {
// it's there
}
else {
// it's not there
}