Replace dots with commas in google app script - javascript

i need help raplacing dots with commas with this script;
function doPost(e) {
//Return if null
if( e == undefined ) {
console.log("no data");
return HtmlService.createHtmlOutput("need data");
}
//Parse the JSON data
var event = JSON.parse(e.postData.contents);
var data = event.data;
var price = event.data;
var at = event.data;
//Get the last row without data
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = Math.max(sheet.getLastRow(),1);
var column = sheet.getRange("C1:C");
var columnn = sheet.getRange("E1:E");
sheet.insertRowAfter(lastRow);
//Insert the data into the sheet
sheet.getRange(lastRow + 1, 1).setValue(event.price);
sheet.getRange(lastRow + 1, 2).setValue(event.at);
column.setNumberFormat("#");
columnn.setNumberFormat("#");
SpreadsheetApp.flush();
return HtmlService.createHtmlOutput("post request received");
}
price and at is coming as eg:347.7100 but i need it as 347,7100
Thanks!

Ciao you could try replace function like:
function doPost(e) {
//Return if null
if( e == undefined ) {
console.log("no data");
return HtmlService.createHtmlOutput("need data");
}
//Parse the JSON data
var event = JSON.parse(e.postData.contents);
var data = event.data;
var price = event.data.replace('.', ',');
var at = event.data.replace('.', ',');
//Get the last row without data
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = Math.max(sheet.getLastRow(),1);
var column = sheet.getRange("C1:C");
var columnn = sheet.getRange("E1:E");
sheet.insertRowAfter(lastRow);
//Insert the data into the sheet
sheet.getRange(lastRow + 1, 1).setValue(event.price);
sheet.getRange(lastRow + 1, 2).setValue(event.at);
column.setNumberFormat("#");
columnn.setNumberFormat("#");
SpreadsheetApp.flush();
return HtmlService.createHtmlOutput("post request received");
}
Note: replace works only with string. If at and/or price are not strings, you have to parse before apply replace like:
...
var price = String(event.data).replace('.', ',');
var at = String(event.data).replace('.', ',');
...

Related

Loop through Googlesheet and grab all rows matching a specific critiera in a user column

I am trying to write a javascript (Googlescript) to loop through a Google Sheet with Specific Tasks assigned to different users and grab all the rows assigned to "UserA" and send an email with the list of all the tasks assigned to userA. Then do the same with UserB
Tasks are not sorted by user.
Columns in the sheet in order are: Name, Description, Status, Owner, Due Date
I am able to send out Emails, with the information problem, the issue is that if you have X amount of Tasks assigned to you get X amount of emails. Which is a problem if you have 10+ tasks....
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ITPM_Tasks");
var lastRow = sheet.getLastRow();
var startRow = 2; // First row of data to process
var numRows = lastRow - 1; // Number of rows to process
// Fetch the range of cells A:P
var dataRange = sheet.getRange(startRow, 1, numRows, 5);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var owner = row[3];
var status = row[2];
var desc = row[1];
var due = row[4];
var due_date = due.toDateString();
var message = 'Reminder: A task is assigned to you\n\n' + desc + '\nwith a due date of '
+ due_date + ' \n\nPlease complete and change status to completed or notify the ITPM Team \n\nThank You'
if (status != 'Complete') { // Prevents sending if status is not completed
var subject = 'Weekly Reminder: A task is assigned to you ';
MailApp.sendEmail(owner, subject, message);
SpreadsheetApp.flush();
}
}
}
Sending all the tasks for each person in one email
This version displays a basic a block of text in a dialog for each email so that I could test it without sending emails
function sendEmails() {
let s = '';
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
const lastRow = sh.getLastRow();
const startRow = 2; // First row of data to process
const numRows = lastRow - 1; // Number of rows to process
const rg = sh.getRange(startRow, 1, numRows, 5);
const vs = rg.getValues();
let oners = {pA:[]};
vs.forEach((r,i) => {
let [name,desc,status,owner,due] = r;
if(status != 'Complete') {
if(!oners.hasOwnProperty(owner)) {
oners[owner]=[];
oners[owner].push(r);
oners.pA.push(owner)
} else {
oners[owner].push(r);
}
}
});
let subject = 'Weekly Reminder: The following tasks are assigned to you.';
oners.pA.forEach(p => {
let msg = `Tasks:\n`
msg += `Owner:${oners[p][0][3]}\n`;
msg += `Subject: ${subject}\n`
oners[p].forEach((r,i) => {
let [name,desc,status,owner,due] = r;
msg += `Task- ${i+1}\n`;
msg += `Desc:${desc}\n`;
msg += `Due Date: ${due.toDateString()}\n`
});
msg += `Please complete and change status to completed or notify the ITPM Team \nThank You\n`;
//MailApp.sendEmail(owner, subject, msg);
msg += `\n\n***********************************\n\n`;
s+=msg;
});
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(`<textarea cols="50" rows="12">${s}</textarea>`),'Simple Dialog')
}
This version should send emails. You may wish to doctor up the message a bit.
function sendEmails() {
let s = '';
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
const lastRow = sh.getLastRow();
const startRow = 2; // First row of data to process
const numRows = lastRow - 1; // Number of rows to process
const rg = sh.getRange(startRow, 1, numRows, 5);
const vs = rg.getValues();
let oners = {pA:[]};
vs.forEach((r,i) => {
let [name,desc,status,owner,due] = r;
if(status != 'Complete') {
if(!oners.hasOwnProperty(owner)) {
oners[owner]=[];
oners[owner].push(r);
oners.pA.push(owner)
} else {
oners[owner].push(r);
}
}
});
let subject = 'Weekly Reminder: The following tasks are assigned to you.';
oners.pA.forEach(p => {
let msg = `Tasks:\n`
msg += `Owner:${oners[p][0][3]}\n`;
msg += `Subject: ${subject}\n`
oners[p].forEach((r,i) => {
let [name,desc,status,owner,due] = r;
msg += `Task- ${i+1}\n`;
msg += `Desc:${desc}\n`;
msg += `Due Date: ${due.toDateString()}\n`
});
msg += `Please complete and change status to completed or notify the ITPM Team \nThank You\n`;
MailApp.sendEmail(oners[p][0][3], subject, msg);
});
}

How to transfer image to Google Drive and save its URL to a Google Sheet in a single script?

I would like to transfer several images from ESP32 to Google Drive and, in the same script, record the image's URL along with date and time in a Google Sheet for future access.
The Script I am using to receive the image on the Google Drive side is as below:
function doPost(e) {
var myFoldername = e.parameter.myFoldername;
var myFile = e.parameter.myFile;
var myFilename = e.parameter.myFilename;
//var myFilename = Utilities.formatDate(new Date(), "GMT", "yyyyMMddHHmmss")+"-"+e.parameter.myFilename;
var myToken = e.parameter.myToken;
var contentType = myFile.substring(myFile.indexOf(":")+1, myFile.indexOf(";"));
var data = myFile.substring(myFile.indexOf(",")+1);
data = Utilities.base64Decode(data);
var blob = Utilities.newBlob(data, contentType, myFilename);
// Save a captured image to Google Drive.
var folder, folders = DriveApp.getFoldersByName(myFoldername);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(myFoldername);
}
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + myFilename);
var imageID = file.getUrl().substring(file.getUrl().indexOf("/d/")+3,file.getUrl().indexOf("view")-1);
var imageUrl = "https://drive.google.com/uc?authuser=0&id="+imageID;
// Send a link message to Line Notify.
var res = "Line Notify: ";
try {
var url = 'https://notify-api.line.me/api/notify';
var response = UrlFetchApp.fetch(url, {
'headers': {
'Authorization': 'Bearer ' + myToken,
},
'method': 'post',
'payload': {
'message': imageUrl
}
});
res += response.getContentText();
} catch(error) {
res += error;
}
//Here is where the code to save imageUrl to Google Sheet was added **********
return ContentService.createTextOutput(myFoldername+"/"+myFilename+"\n"+imageUrl+"\n"+res);
}
What do I have to add to save "imageUrl" to a Google Sheet?
I have tried to save it to the current sheet, that is the sheet this script is attached to but I get error.
In the line indicated above I added the code below that I cut from a script that only writes to the Goggle sheet (no image transfer) but it fails to save the image URL and complains of the line:
var sheet = getSpreadSheet();
//-------------------------------------------------------------------------------
var result = 'Ok'; // default result
if (e.parameter == 'undefined') {
result = 'No Parameters';
} else {
var alarm= e.parameter.alarm;
if (typeof alarm != 'undefined') {
sendEmail("alarm text:" + stripQuotes(alarm));
return ContentService.createTextOutput(result);
}
var sheet = getSpreadSheet(); //---> Error here
var lastRow = sheet.getLastRow();
var newRow = 1;
if (lastRow > 0) {
var lastVal = sheet.getRange(lastRow, 1).getValue();
//if there was no info for (sentEmailIfUnitIsOutForMinutes) checkIfDead() function will append row with 'dead' text
// so checking do we need to override it
if (lastVal == 'dead')
newRow = lastRow; //to overwrite "dead" value
else
newRow = lastRow + 1;
}
var rowData = [];
var namesOfParams=[];
for (var param in parseQuery(e.queryString))
namesOfParams.push(param);
//creatating headers if first row
if (newRow == 1) {
rowData[0] = "Date";
var i = 1;
for (var i=0; i<namesOfParams.length;i++ ) {
rowData[i+1] = namesOfParams[i];
}
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
rowData = [];
newRow++;
}
rowData[0] = Utilities.formatDate(new Date(), timeZone, dateTimeFormat);
for (var i=0; i<namesOfParams.length;i++ ) {
var value = stripQuotes(e.parameter[namesOfParams[i]]);
rowData[i+1] = value;
}
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
//---------------------------------------------------------------------------------
Help highly apreciated.
Thanks
Problem solved with the following script:
var timeZone = "GMT";
var dateTimeFormat = "dd/MM/yyyy HH:mm:ss";
var logSpreadSheetId = "1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8";
// logSpreadSheetId is to be copied from the sheet's URL as follows: https://docs.google.com/spreadsheets/d/1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8/edit#gid=0
function doPost(e) {
var myFoldername = e.parameter.myFoldername;
var myFile = e.parameter.myFile;
//var myFilename = e.parameter.myFilename;
//var myFilename = Utilities.formatDate(new Date(), timeZone, "ddMMyyyyHHmmss")+"-"+e.parameter.myFilename;
var myFilename = Utilities.formatDate(new Date(), timeZone, "ddMMyyyyHHmmss")+".jpg";
var myToken = e.parameter.myToken;
var contentType = myFile.substring(myFile.indexOf(":")+1, myFile.indexOf(";"));
var data = myFile.substring(myFile.indexOf(",")+1);
data = Utilities.base64Decode(data);
var blob = Utilities.newBlob(data, contentType, myFilename);
// Save a captured image to Google Drive.
var folder, folders = DriveApp.getFoldersByName(myFoldername);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(myFoldername);
}
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + myFilename);
var imageID = file.getUrl().substring(file.getUrl().indexOf("/d/")+3,file.getUrl().indexOf("view")-1);
var imageUrl = "https://drive.google.com/uc?authuser=0&id="+imageID;
addLog(myFilename,imageUrl);
return ContentService.createTextOutput(myFoldername+"/"+myFilename+"\n"+imageUrl+"\n"); //+res);
}
function addLog(myFilename,imageUrl) {
var spr = SpreadsheetApp.openById(logSpreadSheetId);
var sheet = spr.getSheets()[0];
var data = sheet.getDataRange().getValues();
var pos = sheet.getLastRow();
var rowData = [];
if(!pos>0){
pos = 1;
rowData[0] = "Date";
rowData[1] = "Image";
rowData[2] = "URL";
var newRange = sheet.getRange(pos, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
pos = pos +1;
rowData = [];
rowData[0] = Utilities.formatDate(new Date(), timeZone, dateTimeFormat);
rowData[1] = myFilename;
rowData[2] = imageUrl;
var newRange = sheet.getRange(pos, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
Also, for simplicity, the sheet and the script now sit on independent files as the script can refer to the sheet using its ID as in:
var logSpreadSheetId = "1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8";.

How to send multiple html form to different google sheet in the same file/database? I have a google sheet which have 3 sheets in total

I have a google sheet which have 3 sheets, and I have 3 html form in total. Html don't run from google app script.
Here's the code I have to send from html from to google sheet. But it only can send to one sheet, I would to send to another sheet. It's a javascript for google app script, it's a .cs file. The code is from here https://medium.com/#dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952cc175
// original gist: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6
function doGet(e){
return handleResponse(e);
}
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
I don't understand this part. I try to add in more variable and PropertiesService. And I can't get the result.
// Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
Here is the solution for your question. https://www.youtube.com/watch?v=V4JMjmwHPEg
I have made a tutorial on youtube you can check the link in the description of youtube for source code.
You have to create duplicate functions for every sheets you have in spreadsheet. Check below code which you need to add in spreadsheet .gs file. for further information you can check the youtube link provided.
// See front-end example at: http://codepen.io/notarazi/pen/yMqyXX
// Usage
// 1. Enter sheet name where data is to be written below
//var SHEET_NAME;
// 2. Run > setup
//
// 3. Publish > Deploy as web app
// - enter Project Version name and click 'Save New Version'
// - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
// 4. Copy the 'Current web app URL' and post this in your form/script action
//
// 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
//Sheet1
try {
var action = e.parameter.action;
if (action == 'create') {
return create(e);
}
else if (action == 'retrieve') {
return retrieve(e);
}
else if (action == 'update') {
return update(e);
}
else if (action == 'delete') {
return del(e);
}
else if (action == 'findRowId'){
return findRowId(e.parameter.findstr);
}
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
//Sheet2
try {
var action = e.parameter.action;
if (action == 'create_1') {
return create_1(e);
}
else if (action == 'retrieve_1') {
return retrieve_1(e);
}
else if (action == 'update_1') {
return update_1(e);
}
else if (action == 'delete_1') {
return del_1(e);
}
else if (action == 'findRowId'){
return findRowId(e.parameter.findstr);
}
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function getDataArr(headers, e){
var row = [];
// loop through the header columns
for (i in headers){
var d= new Date();
if (headers[i] == "tid"){ // special case if you include a unix Timestamp column
row.push(d.getTime());
}else if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
return row;
}
function create0(e){
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": 99}))
.setMimeType(ContentService.MimeType.JSON);
}
function findRowId(data) {
var SHEET_NAME = "Published Online";
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
//var column = sheet.getRange(column + ":" + column); // like A:A
var column = sheet.getRange(1,1,sheet.getLastRow(),1);
var values = column.getValues();
var data1=Number(data);
var row = 0;
var result = 0;
while ( values[row] && values[row][0] !== data ) {
row++;
}
if (values[row][0] === data)
result= row+1;
else
result = -1;
//result += data1;
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "values": result}))
.setMimeType(ContentService.MimeType.JSON);
}
function findInColumn(data) {
var SHEET_NAME = "Sheet1";
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
//var column = sheet.getRange(column + ":" + column); // like A:A
var column = sheet.getRange(1,1,sheet.getLastRow(),1);
var values = column.getValues();
//data=1490461629269;
var testdata = Number(data);
var row = 0;
while ( values[row] && values[row][0] !== testdata ) {
row++;
}
if (values[row][0] === testdata)
return row+1;
else
return -1;
// return ContentService
// .createTextOutput(JSON.stringify({"result":"success", "values": row}))
// .setMimeType(ContentService.MimeType.JSON);
}
function findInColumn_s2(data) {
var SHEET_NAME = "Sheet2";
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
//var column = sheet.getRange(column + ":" + column); // like A:A
var column = sheet.getRange(1,1,sheet.getLastRow(),1);
var values = column.getValues();
//data=1490461629269;
var testdata = Number(data);
var row = 0;
while ( values[row] && values[row][0] !== testdata ) {
row++;
}
if (values[row][0] === testdata)
return row+1;
else
return -1;
// return ContentService
// .createTextOutput(JSON.stringify({"result":"success", "values": row}))
// .setMimeType(ContentService.MimeType.JSON);
}
function findInRow(data) {
var SHEET_NAME = "Published Online";
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var rows = sheet.getDataRange.getValues();
for (var r=0; r<rows.length; r++) {
if ( rows[r].join("#").indexOf(data) !== -1 ) {
return r+1;
}
}
return -1;
}
/***********************************************************************************************************************************************************************************/
//SHEET 1 CREATE
function create(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet1';
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var numColumns = sheet.getLastColumn();
var headers = sheet.getRange(1, 1, 1, numColumns).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = getDataArr(headers, e);
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 1 RETRIEVE
function retrieve(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet1';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var numRows = sheet.getLastRow();
var numColumns = sheet.getLastColumn();
var range = sheet.getRange(1, 1, numRows, numColumns);
var values = range.getValues();
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "values": values}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 1 UPDATE
function update(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet1';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var numColumns = sheet.getLastColumn();
var rowId = findInColumn(e.parameter.tid);
var headers = sheet.getRange(1, 1, 1, numColumns).getValues()[0];
var row = getDataArr(headers, e);
//var rowId = e.parameter.rowId;
var tid= row[0];
// more efficient to set values as [][] array than individually
sheet.getRange(rowId, 1, 1, numColumns).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "tid": tid}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 1 DELETE
function del(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet1';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var rowId = findInColumn(e.parameter.tid);
sheet.deleteRow(rowId);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "rowId": rowId}))
.setMimeType(ContentService.MimeType.JSON);
}
/***********************************************************************************************************************************************************************************/
/***********************************************************************************************************************************************************************************/
//SHEET 2 CREATE
function create_1(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet2';
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var numColumns = sheet.getLastColumn();
var headers = sheet.getRange(1, 1, 1, numColumns).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = getDataArr(headers, e);
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 2 RETRIEVE
function retrieve_1(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet2';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var numRows = sheet.getLastRow();
var numColumns = sheet.getLastColumn();
var range = sheet.getRange(1, 1, numRows, numColumns);
var values = range.getValues();
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "values": values}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 2 UPDATE
function update_1(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet2';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var numColumns = sheet.getLastColumn();
var rowId = findInColumn_s2(e.parameter.tid);
var headers = sheet.getRange(1, 1, 1, numColumns).getValues()[0];
var row = getDataArr(headers, e);
//var rowId = e.parameter.rowId;
var tid= row[0];
// more efficient to set values as [][] array than individually
sheet.getRange(rowId, 1, 1, numColumns).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "tid": tid}))
.setMimeType(ContentService.MimeType.JSON);
}
//SHEET 2 DELETE
function del_1(e) {
var SHEET_NAME = e.parameter.sheet_name || 'Sheet2';
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var rowId = findInColumn_s2(e.parameter.tid);
sheet.deleteRow(rowId);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "rowId": rowId}))
.setMimeType(ContentService.MimeType.JSON);
}
/***********************************************************************************************************************************************************************************/
//SETUP
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
For getting the sheet that you exactly want, you can set another parameter in the Request parameters e.parameters. In each of your forms add a key/value pair defining the name of where you want the form to be submitted. For example:
For the first sheet
sheetName=Sheet1
For the second sheet
sheetName=Sheet2
If you are using a Get Request the URL would look like this:
https://script.google.com/a/your-domain/macros/s/your-id/exec?sheetName=Sheet1.
Then, you would only need to pass that value to the .getSheetByName() like this:
var sheet = doc.getSheetByName(e.parameters.sheetName);

add dependet values and and return all matched

I would like to add another dependency to look for in arrays. So if a user types the name of a student and the subject list,all the results of the supportlist are showed.
I have setup 3 arrays but i'm not sure how to go further.
gs code
function getStudentInfo(studentName){
//var lookupValue = "support";
var ss = SpreadsheetApp.openByUrl(url);
var ws =ss.getSheetByName("logboek1");
var lc =ss.getLastColumn();
//var data = ws.getRange(1, 1, ws.getLastRow(), 2).getValues()[0];
var data = ws.getRange(1, 1, ws.getLastRow(), lc).getValues();
//var index = data.indexOf(lookupValue) + 1;
var studentNameList = data.map(function(r) { return r[0]; });
var subjectList = data.map(function(r) { return r[1]; });
var supportList = data.map(function(r) { return r[4]; });
//Logger.log(supportList);
var position = studentNameList.indexOf(studentName);
if(position > -1){
return subjectList[position];
js code
}
function getEstimate(){
var zipCode = document.getElementById("zip").value;
if(zipCode){
google.script.run.withSuccessHandler(updateEstimate).getCost(zipCode);
}
}
function updateEstimate(cost){
document.getElementById("est").value =cost;
M.updateTextFields();
}
function getEstimate1(){
var studentName = document.getElementById("zip1").value;
if(studentName){
google.script.run.withSuccessHandler(updatestudentInfo)
.getStudentInfo(studentName);
}
}
function updatestudentInfo(info){
document.getElementById("est1").value =info;
M.updateTextFields();
Wat i would like is to add another dependency. So if a user types the studentName, (if the subjects are available for that student)chooses for the subjectList(that are available for that student) and then gets all of the results of the supportlist that belongs by the student.

Google Scripts - delay loop for SMS texting script

I am hitting a Carrier limit when sending out requests to buy item's from sellers.
15-60 messages per minute and under 200 unique recipients a day
How can I stay within the following guidelines if I have 200-500 contacts in my spreadsheet for the script
function sendSms(to, body) {
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/MYAPIKEY/Messages.json";
var payload = {
"To": to,
"Body" : body,
"From" : "+1PHONENUMBER"
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("MYAPIKEY:MYAUTHTOKEN")
};
UrlFetchApp.fetch(messages_url, options);
}
function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 3); // Modified
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
if (row[2].toLowerCase() != "sent") { // Added
try {
response_data = sendSms(row[0], row[1]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
sheet.getRange(startRow + Number(i), 3).setValue(status);
}
}
}
Thank you any help!
This guarantees less than 15 per minute and if you put 200 recipients or less on sheets named for the days of the week (i.e. Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday). Actually you can name them anything you want and use the names over again within the same week as long as you have less that 200 recipients on any one sheet then you be limiting yourself to the maximum number per day.
function sendAll() {
var shA=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];//sheet names
var sheet = SpreadsheetApp.getActive().getSheetByName(shA[new Date().getDay()])
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 3); // Modified
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
if (row[2].toLowerCase() != "sent") { // Added
try {
response_data = sendSms(row[0], row[1]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
sheet.getRange(startRow + Number(i), 3).setValue(status);
Utilities.sleep(4000);//4 seconds
}
}
}
Utilities.sleep()
Date().getDay()

Categories

Resources