Saving a floating value to a google sheet using a script - javascript

I want to use google script to make a request and save some data on google sheet.
The problem is when I try to pass some non integer values as parameters in the request.
I think it's something to do with the fact that sheets uses comma for separating decimal from integer while my program sends the numbers separated by a dot.
This is where I am now:
const doPost = (event) => {
console.log(`doPost`, JSON.stringify(event));
const { parameter } = event;
const { temp, peso } = parameter;
var date = new Date();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([date, parseFloat(temp), peso]);
}
When I make a post request with parameters: { temp:1.234, peso:1.234 } the result on google sheet is a big mess.
Does someone have any idea how to fix this?
edit:
function Test(){
var sheet = SpreadsheetApp.getActiveSheet();
var d = 1.23456;
var date = new Date();
sheet.appendRow([date, d]);
}
This works fine... don't know if it can help you debug.

Post Data to Sheet
I don't actually do this all that much so I am by no means an expert at it
function doPost(e) {
Logger.log(e.postData.contents);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
let data = JSON.parse(e.postData.contents);
sh.appendRow([data.first,data.second])
}
function sendData(obj) {
const url = ScriptApp.getService().getUrl();
const params={"payload":JSON.stringify(obj),"muteHttpExceptions":true,"method":"post","headers": {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
UrlFetchApp.fetch(url,params);
}
function saveMyData() {
sendData({first:"1.234",second:"1.432"});
}
This worked for me.

Finally figured it out!
The problem was in the setting of the google sheet file.
I'm from Italy so it enters as defult the Italian format. For some reasons this mess up all the new entries. The solution is very simple: change the format to the english one and the problem should solve itself!

Related

Google Sheets - Sending Row to Another Spreadsheet

Written a Google Sheet where when a button is pressed a collated row of data is sent to a different Google Sheet. It was launched six months ago among colleagues that have full permissions to both sheets. The reason for this post was that 1 in 10 submissions goes missing and never arrives to be added to the secondary Google Sheet. Thus wondering if anyone had any ideas as to if there was an issue with my code.
sh.getRange("j7").setValue('=now()');
var range = sh.getRange('J7:R7'); //Fixed range of where the row/data is collated
var data = range.getValues();
var tss = SpreadsheetApp.openById('SHEET ID');
var ts = tss.getSheetByName('Main');
ts.getRange(ts.getLastRow()+1,1,1,9).setValues(data);
Many thanks for any ideas...
Try this:
function lfunko() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Enter Your Sheet Name");
sh.getRange("J7").setFormula('=now()');
var range = sh.getRange('J7:R7');
var data = range.getValues();
var tss = SpreadsheetApp.openById('SHEET ID');
var ts = tss.getSheetByName('Main');
ts.getRange(ts.getLastRow() + 1, 1, data.length, data[0].length).setValues(data);
}

How to get formatted array on Google AppScript?

I have a code that takes each cell from a gsheet and changes the format using appscript but this does not correct it back on the google sheet. I used this because even though the format was correct on the gsheet, when getvalue() is used, the number loses its format.
var Qty1 = ss.getRange(i, 15).getValue();
var Qty1Format = Qty1.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
//Output has a thousands separator and two decimal places.
This takes a lot of time to run and as a result I am looking for alternative ways to correct the format.
I was thinking of getting all the values of the column as an array and I am looking to convert the array in the format needed and paste this back into the sheet.
I've had attempts at coding this but would be grateful for any help on how to change format for the array or alternative ways of achieving the outcome.
Sample code attempt:
function copypastetest() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").activate();
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var rng = ss.getRange("C2:"+"c"+lr).getValues();
var frng = rng.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
var copy = ss.getRange("C2:"+"c"+lr).setValues(frng)
}
Further Edit:
#Cooper's answer is spot on. However I'm might not have asked the right question to solve my problem. I am ultimately looking to take values from the google sheet and replace placeholders into a google doc.
See below (although the number is formatted it still appears to be unformatted in the formula bar - and I should have noticed this before but i did not)
So how I can format the array (or get an array that is formatted in the first place to come on my Logger.log on the appscript?
Here is the rest of the script for you to understand what I am looking to achieve,
function generatetest() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").activate();
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var rng = ss.getRange("A1:"+"F"+lr).getValues();
for (var i =2;i<=lr;i++){
if(ss.getRange(i, 1).getValue()){
var client = rng[i-1][1];
var email = rng[i-1][2];
var documentId = DriveApp.getFileById('1j36HPQkTPc0R4GCtA0XKcmeHUVPsgBKoyNIl93HFhp0').makeCopy().getId();
DriveApp.getFileById(documentId).setName(client);
var body = DocumentApp.openById(documentId).getBody();
body.replaceText('{Name}', client).replaceText('{Email}', email)
}
else {}
}
}
If I understood your issue correctly, I believe it can be solved by using the getDisplayValues() method of class Range. This method copies the format of the cell and returns the formatted string.
var rng = ss.getRange("C2:"+"c"+lr).getDisplayValues()
References:
Range.getDisplayValues()
I tried this and it seems to work, if I understand your issue.
function runOne() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet22');
const rg=sh.getRange(1,1,sh.getLastRow());
const vA=rg.getValues();
vA.forEach(function(r,i){
sh.getRange(i+1,2).setValue(r[0]).setNumberFormat('#,##0.00');
})
}
Here's my start data:
1000000.33
2000000.34
3000000.35
4000000.36
5000000.37
6000000.38
7000000.39
8000000.4
9000000.41
10000000.42
11000000.43
12000000.44
13000000.45
14000000.46
15000000.47
16000000.48
17000000.49
18000000.5
And here's my ending data:
1000000.33,1000000.33
2000000.34,2000000.34
3000000.35,3000000.35
4000000.36,4000000.36
5000000.37,5000000.37
6000000.38,6000000.38
7000000.39,7000000.39
8000000.4,8000000.4
9000000.41,9000000.41
10000000.42,10000000.42
11000000.43,11000000.43
12000000.44,12000000.44
13000000.45,13000000.45
14000000.46,14000000.46
15000000.47,15000000.47
16000000.48,16000000.48
17000000.49,17000000.49
18000000.5,18000000.5
Here's what the sheet looks like:
I use this script a lot for viewing and editing number formats on a spreadsheet and I find it helpful to solve formatting issues. There's probably an easier way but I haven't found it yet.
function getandSetActiveRangeFormats() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getActiveRange();
var fA=rg.getNumberFormats();
var html='<style>th,td{border:1px solid black;}</style><table><tr><th>Item</th><th>A1 Notation</th><th>Number Format</th><th>Enter Format</th><th>Set Format</th></tr>';
var item=1;
var row=rg.getRow();
var col=rg.getColumn();
fA.forEach(function(r,i){
r.forEach(function(c,j){
var txt=Utilities.formatString('<input type="text" id="RC-%s-%s" />',row+i,col+j);
var btn=Utilities.formatString('<input type="button" value="Set Form" onClick="setFormat(%s,%s);" />',row+i,col+j);
html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',item++,sh.getRange(row + i,col + j).getA1Notation(),fA[i][j],txt,btn);
});
});
html+='</table><input type="button" value="Exit" onClick="google.script.host.close();" />';
html+='<script>function setFormat(row,col){var f=document.getElementById("RC-"+row+"-"+col).value;google.script.run.setFormat(row,col,f);}</script>';
var ui=HtmlService.createHtmlOutput(Utilities.formatString(html));
SpreadsheetApp.getUi().showModelessDialog(ui, "Display and Set Active Range Formats")
}
function setFormat(row,col,format) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.getRange(row,col).setNumberFormat(format);
}

Exception error relating to method signature

I'm super new to JavaScript, am an editor by trade, but need to create a Google Calendar view from a Google Sheet for story assignments for my writers. I've gone through a tutorial on how to make this work and have fixed a number of problems with the code. I'm stuck on what I think is the final issue. It relates to the method signature. The error message is:
Exception: The parameters (String,String,String,String,String,String)
don't match the method signature for
CalendarApp.Calendar.createAllDayEvent. (line 20, file "Code")
Here's the code. Can anyone help???
function myFunction() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var calendarId = spreadsheet.getRange ("N8").getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);
var signups = spreadsheet.getRange("G8:L124").getValues();
for (x=6; x<signups.length; x++) {
var shift = signups[x];
var author = shift[0];
var newsletterdate = shift[1];
var livedate = shift[2];
var duetoproductiondate = shift[3];
var duetocopyeditdate = shift[4];
var duetocontenteditdate = shift[5];
eventCal.createAllDayEvent(author, newsletterdate, livedate, duetoproductiondate, duetocopyeditdate, duetocontenteditdate);
}
}
It seems there is no signature for this method that has 6 parameters. The maximum I noted was 5 on this documentation: https://developers.google.com/apps-script/reference/calendar/calendar-app
You must review the arguments you are passing when calling the function and choose the most suitable method signature.

Google Sheets: Trying to GetValue -> SetValue with Bitcoin Prices and print it anywhere in the sheets. 2 Codes

My goal:
I'm trying to print (or stamp) the value of bitcoin each time there is word called "printprice" anywhere in the sheet.
My problem:
I have been very unsuccessful getting this as I have been trying to get the solution from two different codes
This is what I'm trying to achieve:
function onEdit() {
// simple timestamp -- when a single "T" is entered in a cell, replace it with a timestamp
// see https://productforums.google.com/d/topic/docs/rC6MpQDC7n4/discussion
var cell = SpreadsheetApp.getActiveRange();
if (cell.getValue() == "Timestamp") {
cell.setValue(new Date());
}
}
^ this works and prints new Date each time there's word "timestamp" anywhere in the sheet.
What I have been trying to do is to combine the data above with the down below without any success.
/* USAGE:
* Sheet -> Tools -> Script Editor...
* Paste this script
* Update the map (below) to your preferences
* Create a button in your Sheet and Assign Script: `test`
* et voila profit
*/
function test() {
// maps currencies.tokens to sheet ranges
getPrices({
'USD': {
'ETH': 'G6',
'DASH': 'H6',
'LTC': 'I6',
'GNT': 'J6',
'REP': 'K6',
'BAT': 'L6'
}
});
}
function getPrices(model) {
for (var currency in model) {
var tokens = Object.keys(model[currency]).toString();
var url = 'https://min-api.cryptocompare.com/data/price?fsym=' + currency + '&tsyms=' + tokens;
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = JSON.parse(response.getContentText());
for (var token in model[currency]) {
updatePrice(
model[currency][token],
json[token]
);
}
}
}
function updatePrice(range, price) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(range).setValue(1/price);
}
Hopefully you can provide help as this is a learning process for me as well!
Kind Regards Johan

Timing Tool for work

I have built a tool for timing indirect workers, it consists of a start and stop button which both place a time stamp into the google sheet and then calculates the difference to record a time. It works great however when I share it with some people it does not allow them to use it saying that they do no have access to run the script. If they open script editor they can manually run it however that will no fly because I will be sending this out to approximately 50 people.
Here is the code and start and stop are two different scripts. Please let me know if I am missing something and I appreciate the help. Thanks
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var start = new Date();
function StartScript() {
var last = ss.getLastRow();
ss.getRange(last+1,1).setValue(last+1)
var source = ss.getRange(last+1,1).getValue();
source = Number(source);
if (source <= 16) {
ss.getRange(last+1,2).setValue(start);
}
else {
ss.getRange(last+1,2).setValue("Stop Timing");
}
}
function stop() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var date = new Date();
var last1 = ss.getLastRow();
ss.getRange(last1, 3).setValue(date);
var lastrow = ss.getLastRow()
ss.getRange("D" + (lastrow)).setFormula("=C" + (lastrow) + "-B" + (lastrow));
}

Categories