How to translate decimal number to time in spreadsheet - google-apps-script

THrough Table Capture extension I have copied a html table from a webpage into the google spreadsheet.
In that table, there is a column in decimals for ex :
12.4
I want to change this into
12:40:00
If I normally replace . with : then it's replacing to
12:04:00

You should give a try with Format => Number => Time
You should open a new script by Tools=> Script Editor and take a look at that which is a tutorial to delete row and you'll need to adapt it to change row values. You'll find all the needed doc here
And your code may look like this :
for each row{
var string = new array(2);
//Split the string a the .
string = row.split(".");
// if the second part is like 4 in 12.4 you set it to 40
if (string[1].lenght() == 1)
string[1] += 0;
// Set the row value to the format you like, here : 12:40:00
row.setValue(string[0] + ":" + string[1] + ":00");
}

Related

How to assign google script function to image button with parameter [duplicate]

I can successfully assign scripts to images in Google spreadsheets. My problem is with parameter passing.
I have this script to write the current time on a cell.
function Time(cell){
var d = new Date();
var timeAsString = d.getHours() + ":" + d.getMinutes() + "/" + d.getSeconds();
SpreadsheetApp.getActiveSheet().getRange(cell).setValue(timeAsString);
};
I need a bunch of buttons to do this with diferent cells, so I wish to specify which cell the time goes to by parameter.
Many tx.
Sorry, but this really doesn't solve my problem. I don't want user input. The idea is to have a button associated to each cell. The user just presses a button and the cell is filled with a timestamp. If the user must input the cell name, it's ruined. Current solution works but it's ugly:
function Time(cell){
var d = new Date();
var timeAsString = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
SpreadsheetApp.getActiveSheet().getRange(cell).setValue(timeAsString);
};
function TimeB12(){Time('B12')};
function TimeB13(){Time('B13')};
// about 500 more cells...
I then associate script TimeB12 to button next to cell B12, and so on.
Yes you can xD
you must use a prompt , ask the user to input string : Browser.inputBox
documentation : https://developers.google.com/apps-script/reference/base/browser#inputBox%28String%29
And your script use this string exemple : 'A1'
ex : SpreadsheetApp.getActiveSheet().getRange("A1")

How to take data from Google Sheet and create a pre-filled link to Google Form

So when generating a pre-fillend in link for a Google Form I have observed the following:
https://docs.google.com/forms/d/e/{Form ID}/viewform?usp=pp_url&entry.1686820921=Field1+Value&entry.551739295=Field2+Value&entry.1561066553=Field3+Value
Based on this example I created VIA the Google Form > Get pre-filled link, you can see how easy it would be to replace the values and generate this URL based on values pulled form a spreadsheet. Now when I try to do this there are some obvious complications like what if there is a space, what if there is a new line
Google Forms seems to have replaced a space with a + and a new line with a %0A, it does not seem to use the default encoded URL chr (shown below) as most forms use.
Space %20
" %22
< %3C
> %3E
# %23
% %25
| %7C
this is taken from :https://developers.google.com/maps/documentation/urls/url-encoding.
Is there a function or method that I can call to encode the value to a Google Form URL safe values?
Example
sheet.getRange(A1).getValue().someFunctionThatEncodes();
or
someFunctionThatEncodes(sheet.getRange(A1).getValue());
If not does anyone have a function they could share that I would pass a value to it and it would return the encode version that Google Forms requires?
FYI I have tested the encodeURIComponent() and it seems to go a little over kill on it and I get extra special CHRs that don't translate properly
For example, the following values are converted to the pre-filled link,
sample1 ' "<>#%|'
sample2 ' "<>#%|'
sample3 ' "<>#%|'
the following encoded link can be retrieved.
https://docs.google.com/forms/d/e/###/viewform?usp=pp_url&entry.1234567890=sample1+'+%22%3C%3E%23%25%7C'&entry.1234567891=sample2+'+%22%3C%3E%23%25%7C'&entry.1234567892=sample3+'+%22%3C%3E%23%25%7C'
When above link is decoded, it becomes as follows.
https://docs.google.com/forms/d/e/###/viewform?usp=pp_url&entry.1234567890=sample1 ' "<>#%|'&entry.1234567891=sample2 ' "<>#%|'&entry.1234567892=sample3 ' "<>#%|'
From above situation, as a sample script, when above values of sample1 ' "<>#%|', sample2 ' "<>#%|' and sample3 ' "<>#%|' are used for the pre-filled link of your URL, the script is as follows.
Sample script:
When you use this script, please set url and query as follows.
const url = "https://docs.google.com/forms/d/e/{Form ID}/viewform";
const query = {
"usp": "pp_url",
"entry.1686820921": `sample1 ' "<>#%|'`,
"entry.551739295": `sample2 ' "<>#%|'`,
"entry.1561066553": `sample3 ' "<>#%|'`,
}
// This script is from https://gist.github.com/tanaikech/70503e0ea6998083fcb05c6d2a857107
String.prototype.addQuery = function(obj) {
return this + Object.keys(obj).reduce(function(p, e, i) {
return p + (i == 0 ? "?" : "&") +
(Array.isArray(obj[e]) ? obj[e].reduce(function(str, f, j) {
return str + e + "=" + encodeURIComponent(f) + (j != obj[e].length - 1 ? "&" : "")
},"") : e + "=" + encodeURIComponent(obj[e]));
},"");
}
const endpoint = url.addQuery(query);
console.log(endpoint);
In this case, the value of query parameter is encoded by encodeURIComponent.
Reference:
encodeURIComponent()
encodeURIComponent would indeed do the trick if you use JS; if you use google sheets, you have ENCODEURL as a function, so you can do sth like =HYPERLINK(CONCAT("https://docs.google.com/forms/d/e/<some form id>/viewform?usp=pp_url&entry.<some entry id>=Option+2&entry.<some entry id>=",ENCODEURL(F14)))
You start with what you get from Get pre-filled link using field values like FFFIRSTNAMEEE (that are easy to spot). Then, just replace parts that shall be individual and make sure to use ENCODEURL. When also using HYPERLINK, links become click-able in the sheet as well.
Assuming you start out with https://docs.google.com/forms/d/e/``<some form id>/viewform?usp=pp_url&entry.<some entry id>=Option+2&entry.<some entry id>=AAANSWERRR - and apply above formula and put "hey there" into cell F14, you'd get https://docs.google.com/forms/d/e/<some form id>/viewform?usp=pp_url&entry.<some entry id>=Option+2&entry.<some entry id>=hey%20there

Google Apps Script - Format value with 4 digits

I have a variable which needs to be formatted into a 4 digit format,
i.e. 4 would be 0004, or 38 would be 0038
I've tried using getNumberFormat as below but this gives me no luck. Looking around I'm struggling to find a clean solution to this?
var stringVal = 38;
var prettyVal = stringVal.getNumberFormat('0000');
worksheet.getRange(row+1, AUTOINC_COLUMN+1).setValue("GL"+prettyVal);
EDIT - It needs to be formatted before being placed into my spreadsheet - since I'll append the string 'GL' before the value to form the key
To achieve expected result, use below option
var stringVal = 38;
var format = "0000"
var prettyVal = stringVal.toString().length < 4 ? format.slice(stringVal.toString().length) + stringVal.toString() : stringVal ;
console.log(prettyVal)
I'm assuming you are referring to a spreadsheet. Once you have placed the value in a cell or cells you can setNumberFormat.
var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A1");
range.setValue(38);
range.setNumberFormat("000#");

Convert binary data to HEX in Google sheets

I have a Google sheet document with a column containing binary data. The binary data is 4 32-bit numbers. This is an example ASCII hex representation of that binary data from one cell: c0a80123000006150000000180004203.
Is there a way in Google sheets to convert this binary number to hex string. I'm looking for something like: BIN2HEX(data[0]) = "0xc0". Regular BIN2HEX doesn't work because the data is larger than it can handle.
Raw text sample file. Converted google sheet.
Update:
Based on one suggestion I've created a Google API script to process the binary data. However, the results come strange to say the least.
function extractip(binary_data) {
var blob = Utilities.newBlob(binary_data);
var ip1 = blob.getBytes()[0];
var ip2 = blob.getBytes()[1];
var ip3 = blob.getBytes()[2];
var ip4 = blob.getBytes()[3];
return Utilities.formatString("%u.%u.%u.%u", ip1, ip2, ip3, ip4);
}
The first 4 bytes in the binary blob represent an IP address, in the form of 192.168.0.X in the attached example. However, the output comes back something like -17.-65.-67.-17.
How about this modification?
At Google Apps Script, the data which was converted by Utilities.newBlob(data).getBytes() is the bytes array of the signed hexadecimal. It is required to convert the bytes array to the unsigned hexadecimal.
Modified script:
function extractip(binary_data) {
var byteAr = Utilities.newBlob(binary_data).getBytes();
return byteAr.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2)}).join("");
}
Note:
When you use this, for example, please put =extractip(G2) to "H2" like your shared spreadsheet.
Edit:
If you want to directly retrieve the decimal number like 192.168.0.X, please modify like below. This is a sample modification. So please modify it to your situation.
From:
return byteAr.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2)}).join("");
To:
return byteAr.map(function(e) {return e < 0 ? e + 256 : e}).join(",");

Google Script insertSheet not accepting string object?

So I am taking data from a spreadsheet, putting the relevant parts into an array and writing it back to a new spreadsheet. The data is coming from a google form and not everyone had an input for every question so I am taking only the questions that are not null. Which causes the length of my array to be variable
So I have taken it down to its most barest steps and I am stuck at the part where you insert the sheet, it works fine on a iteration of 1, but when I do it on a loop there is an error.
for (j=2; j <= 3 ; j++)// I have 23 iterations, but I stopped at 2 for now
{
var cellLocation = new String ("B" + j + ":AC" + j);
Logger.log("J is " + j + "Cell location " + cellLocation);
var workingRange = buySheet.getRange(cellLocation);
var customer = workingRange.getValues(); //this produces a range of the row
Logger.log("Range is " + workingRange.getA1Notation() + " data is " + customer[0][0]);
//At first I thought it was the range- so I broke everything out into the tiniest step
var nameCustomer = new String(customer[0][0]);
Logger.log("nameCustomer is " + nameCustomer);
//this correctly prints out the names as strings- through 23 iterations
var create = buySheet.insertSheet(nameCustomer);
//this is a sheet object with the customers name- fails after the first iteration, and creates sheets with blank names -
}
This is the reference I am using: https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#insertSheet(String)
I have commented out everything after this to solve this one sticking point. I have tried instantiating the string outside the loop. I can post the logs, I am using real data I have so I would have to blur out peoples names.
It works for the first round, and it works if I manually type a string.
I figured it out! When I created a new sheet it moved the active sheet to the new sheet. So at the end of the loop I have to reset the active sheet to the first sheet where the data I want it is.
Seems so obvious in retrospect.