running a script to import a csv from gmail attachment into a Google Sheet and there is a timestamp column.
We are looking to modify those value to be just Date and remove the timestamp before writing the csv contents into the Google Sheet.
Any tips on how we might do that? We're very much beginners here so any help would be appreciated.
As the function name says this function accepts a CSV string and converts it to a 2D Array. It then iterates down column 1 removing the time part of the datetime and then it loads a sheet.
function getCSVConvertToArrayRemoveTimeAndLoadSheet(csv) {
var csv=csv||getCSV();
var vA=Utilities.parseCsv(csv);
for(var i=0;i<vA.length;i++) {
vA[i][0]=new Date(new Date(vA[i][0]).getFullYear(),new Date(vA[i][0]).getMonth(),new Date(vA[i][0]).getDate());
}
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet178');
var rg=sh.getRange(1,1,vA.length,vA[0].length);
rg.setValues(vA);
}
I used the below function to create CSV String from a simple spreadsheet with column 1 as a timestamp.
function getCSV() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet177');
var rg=sh.getDataRange();
var vA=rg.getValues();
var csv="";
for(var i=0;i<vA.length;i++) {
if(i>0) csv+='\n';
csv+=vA[i].join(',');
}
//Logger.log(csv);
return csv;
}
Utilities.parseCsv()
Related
I am a newbie of Google charts. I am trying to change data type of a google chart data table column after this has been created. Searching for a solution over the internet I have bumped into this solution for a datetype column. May you generalize it in order to change a chosen data type column from number to string? I would like to change it so that I can visualize some strings in a number column, as you can see in the attached screenshot.
My trial is:
<script type="text/javascript">
function drawVisualization() {
$.get("delivery_pl_daily_test.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
var columns = [];
for (var i = 0; i < data.getNumberOfColumns(); i++) {
columns.push(i);
}
var view = new google.visualization.DataView(data);
columns[0] = {
calc: row,
label: arrayData[0][0],
type: 'string'
};
view.setColumns(columns);
Thanks in advance.
Drigo
what you have looks close,
but calc should be a function,
that returns the value for the column.
the calc function receives the data table and current row as arguments.
here, I simply return the formatted value of the column.
columns[0] = {
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
},
label: arrayData[0][0],
type: 'string'
};
I created a Form for requesting new student Google account. I want a Sheets Script to email the person who submits the Form the new account information, which is created via a formula on a "Results" sheet.
function Notification() {
// Send email notice for accounts
var lastRow = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getLastRow();
var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getRange("A" + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
var AccountName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getRange("H" + lastRow);
var Password = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getRange("I" + lastRow);
var PW = Password.getValue();
var Account = AccountName.getValue();
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results").getRange("G" + lastRow);
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'Account Request - Account Name: ' + Account + ' Password: ' + PW; // Second column
var subject = 'Google Account Request';
MailApp.sendEmail(emailAddress, subject, message);
}
This script is triggered on a new Form Submit. Attempting to pull the values from the last created row queried to a "Results" sheet, using lastRow to find the latest entries row, from select columns. Script runs without error, but no email is sent, telling me that it's not getting the values, or returning null values.
This is the sheet its pulling data from
You are only sending row 2 because you are retrieving only one value (Password.getValue() and AccountName.getValue()). Consider the difference between getValue versus getValues.
On the other hand, by declaring a range such as getRange("H2:H") ("Account Name") you are including every row in the spreadsheet, including rows with and without content.
How would I make it pull the values from the last created row?
There are two options:
getlastRow() (the "Sheet" versus "Range" version) "returns the position of the last row that has content" doc ref here. In fact, that item of documentation has a good example of how to declare a Range using the command.
there is another (very useful) utility described on StackOverflow that is a favourite of mine. This describes the number of contiguous rows, in a column, with content.
I suggest that you declare the range using getRange(row, column, numRows, numColumns).
"row" having been determined using one of the methods described above, "numRows"=1. Then getValues for that range will include only the values in that row, and your email will be sent only in relation to that row.
I want to generate mongo objectid for the documents to be inserted as new with the timestamp value overwritten. so i used below code to get objectid.
var oIdWithTimestamp = function (timestamp) {
// Convert string date to Date object (otherwise assume timestamp is a date)
if (typeof (timestamp) == 'string') {
timestamp = new Date(timestamp);
}
// Convert date object to hex seconds since Unix epoch
var hexSeconds = Math.floor(timestamp / 1000).toString(16);
// Create an ObjectId with that hex timestamp
var constructedObjectId = mongoose.Types.ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
};
but if i want to insert 2 documents with same timestamp it doesn't fullfill the need. I noticed there is a get_inc function used to add incrementor value to objectids. And 16777214 different objectids can be generated using same timestamp. Any help regarding how to use this incrementor to get unique timestamp upto 16777214 is appreciated.
I have tried generating random mongo objectid using below snippet.
var bson = require('bson');
var generateObjIdFromTime = function(spefictime) {
spefictime = ~~(spefictime/1000);
return bson.ObjectID(spefictime);
}
It generates random mongo objectids with given timestamp.
I have a Google Sheet where information from a Google Form is dumped. Two of the columns create a date range and I would like for the sheet to automatically create a new row of information for every date of the range and copy all the other information from the original row for every row that is created. In the end, every date in the range has it's own row regardless of it being 2 days or 25 and all the the information gathered through the form be present for each day
Here is an example
Here's a function that will do the trick for you. My spreadsheet is below after running. I just append it to the bottom of the starting data.
function convertDateRangetoRows()
{
var ss=SpreadsheetApp.getActive();
var sht=ss.getActiveSheet();
var rng=sht.getDataRange();
var rngA=rng.getValues();
var rngB=[];
var day=86400000;
rngB.push(rngA[0]);
for(var i=1;i<rngA.length;i++)
{
rngB.push(rngA[i]);
if(rngA[i][0] && rngA[i][1] && rngA[i][0]!=rngA[i][1])
{
var dt0=new Date(rngA[i][0]);
var dt1=new Date(rngA[i][1]);
var days=(dt1.valueOf()-dt0.valueOf())/day;
var dt=dt0.valueOf();
for(j=0;j<days;j++)
{
dt+=day;
rngB.push([Utilities.formatDate(new Date(dt), Session.getScriptTimeZone(), "MM/dd/yyyy"),'',rngA[i][2],rngA[i][3],rngA[i][4]]);
}
}
var intermediate='nothing';
}
var rngb=sht.getRange(sht.getLastRow()+1,1,rngB.length,rngB[0].length);
rngb.setValues(rngB);
var end='the end is near';
}
I come from an SQL background and recently started using Firebase for building an ionic shopping cart. This is the database schema:
To retrieve a user's cart, i used the following
var user_id="user1"; // Temporary initialised
var refCart = new Firebase("https://testing.firebaseio.com/cart");
var cart=$firebase(fireBaseData.refCart().child(user_id)).$asArray();
This gives the result:
item1 1
item2 2
item3 5
So tried using foreach()
var refMenu = new Firebase("https://testing.firebaseio.com/menu");
refCart.child(user_id).on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item_id = childSnapshot.name();
var qty = childSnapshot.val();
//var data= refMenu.child(item_id).val();
// val is not a function
//var data= refMenu.child(item_id).exportval();
// exportval is not a function
//var data = $firebase (refMenu.child(item_id)). $asArray();
// Give me an array of objects , ie attributes - OK! But what to do next ?
//console.log("DATA",data );
console.log("Item",item_id+" "+qty);
});
});
How can i use item_id to retrieve item details.
Is it the correct way of doing data retrieval from multiple tables?
Update:
Using on() function , i managed to get the item attributes.
refMenu.child(item_id).on("value", function(snapshot) {
console.log("Price",snapshot.val().price);
});
But is there any better implementation for the same.
Is there any better ways to retrieve (from the server side) specific attributes for the item.
Like in SQL
SELECT name,price, ... from menu;
NOTE: .on('event', callback) method will call your callback every time the event is fired.
If you need to retrieve data from a reference once, you should use: .once('event', callback)
NOTE2: snapshot.val() will give you a JSON object that you can assign to a variable
I would do it this way:
refCart.child(user_id).on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item_id = childSnapshot.name();
var qty = childSnapshot.val();
refMenu.child(item_id).once("value", function(snapshot) {
var item = snapshot.val()
console.log(item.name +' '+ item.price)
});
});
});
Hope it helps ;)