I am reading the data from Google spread sheet using Google app script.
in one of the cell(sprint version) of spreadsheet I have mentioned the value as 56 but when I am reading the value it is returning 56.0. I don't know why
Below method, I wrote to read the value from spreadsheet
function readAndSetTimePeriodMetaData() {
var timePeriodArray = new Array();
var masterSheetID = "My Google Sheet ID";
var masterSheet = SpreadsheetApp.openById(masterSheetID);
var timePeriodDataSheet = masterSheet.getSheetByName("Time Period MetaData");
data = timePeriodDataSheet.getDataRange().getValues();
var range = timePeriodDataSheet.getRange(1,2);
var sprintVersion = range.getValue(); //it is returning 56.0
var range = timePeriodDataSheet.getRange(2,2);
var monthValue = range.getValue();
var range = timePeriodDataSheet.getRange(3,2);
var quarterValue = range.getValue();
Logger.log(sprintVersion)
}
I solved it by using toFixed(0)
var sprintVersion = range.getValue().toFixed(0);
Related
I have code to calculate two cells by formula this is my code :
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("sheet29");
var maxR = sh.getMaxRows();
var first = sh.getRange(maxR,6,1);
var second = sh.getRange(maxR,7,1);
var calculate = sh.getRange(maxR,8,1);
first.setValue("2");
second.setValue("2");
var q = "F6"; // I want to change it to some thing like var q = first...;
var qq = "G6"; // I want to change it to some thing like var q = second...;
var formula= ("=sum("+q+"+"+qq+")");
calculate.setValue(formula);
}
This code is fine calculate by formula by this code
var formula= ("=sum("+q+"+"+qq+")");
calculate.setValue(formula);
what I need, I don't know what is the name of cells to calculate, this dynamic. Any way to find the name of cell by range or another method
You can get the A1 notation of a range by using range.getA1Notation() method and use it to set formula. Change your code
From:
var q = "F6";
var qq = "G6";
To:
var q = first.getA1Notation();
var qq = second.getA1Notation();
Reference:
Range.getA1Notation()
I have two functions in a google sheet that are meant to loop through a single column containing the file IDs of files in google drive, issuing a Properties.get to retrieve a single property "LastReview" for each document and paste all of the LastReview times in the next available column.
I'm having trouble getting the loop in "loopForMetadata" to work. I want it to acquire a list of all the LastReview times associated with each fileID and then post that to the next available column so that all of the LastReview times align with the fileIDs.
function getProperty(fileId) {
var propertyKey = 'LastReview'
var fileId = '1UaQkJU8r1kE9sxpFg6OD8aOuUCoRnSpB9Agg_R9HJ3s'
var response = JSON.stringify(Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value);
var key = "value";
var resposeNoQuote = response.replace(/\"/g, "")
Logger.log(resposeNoQuote);
}
function loopForMetadata() {
var columnNeeded, data, lastColumn, sh;
sh = SpreadsheetApp.getActiveSheet();
lastColumn = sh.getLastColumn();
data = sh.getRange(1, 1, 1, lastColumn).getValues();//Get 2D array of all values in row one
data = data[0];//Get the first and only inner array
columnNeeded = data.indexOf('ID') + 1;//Arrays are zero indexed- add 1
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2, columnNeeded, lastRow - 1, 1);
// Get array of values in the search Range
var rangeValues = searchRange.getValues();
// Loop through array and if condition met, add relevant
// background color.
var resultValues = []
for (i = 0; i < rangeValues.length; i++) {
resultValues.push(getProperty(rangeValues[i]));
Utilities.sleep(10);
}
Logger.log(resultValues);
};
I believe your goal as situation as follows.
You want to retrieve the values using the key of LastReview in the property from the files of fileId.
You want to put the retrieved values to the same row of fileId in the next available column.
You want to achieve this using Google Apps Script.
Modification point:
In your script,
getProperty() doesn't return the values.
resultValues is not put to the Spreadsheet.
When you want to retrieve the value of the key LastReview, Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value directly returns the value.
As an important point, when the file of fileId has not property of the key LastReview, it seems that Drive.Properties.get() occurs an error. So in this modification, as a simple workaround, I used the try catch.
When above points are reflected to your script, it becomes as follows.
Sample script:
function loopForMetadata() {
var columnNeeded, data, lastColumn, sh;
sh = SpreadsheetApp.getActiveSheet();
lastColumn = sh.getLastColumn();
data = sh.getRange(1, 1, 1, lastColumn).getValues();//Get 2D array of all values in row one
data = data[0];//Get the first and only inner array
columnNeeded = data.indexOf('ID') + 1;//Arrays are zero indexed- add 1
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2, columnNeeded, lastRow - 1, 1);
var rangeValues = searchRange.getValues();
var resultValues = []
// I modified below script.
for (i = 0; i < rangeValues.length; i++) {
var fileId = rangeValues[i];
var value = "";
try {
value = Drive.Properties.get(fileId, 'LastReview', { visibility: 'PUBLIC' }).value;
} catch(e) {}
resultValues.push([value]);
// Utilities.sleep(10); // I'm not sure whether this is required.
}
sheet.getRange(2, lastColumn + 1, resultValues.length, 1).setValues(resultValues);
Logger.log(resultValues);
};
Note:
Please confirm whether Drive API is enabled at Advanced Google services, again.
Reference:
Properties: get
I need a help reading cell value using either java or google script. The cell I am trying to read has a formula. When my script reads the data I get #DIV\0! error.
here is my simple script:
function readData(){
var Keys = "1Vp_fjFVFXHDjJRXl7C6mNzCK66jVB1I1BjieaZK6P";
var SheetName = "AAL";
var WR;
SS = SpreadsheetApp.openById(Keys);
Sheet = SS.getSheetByName(SheetName);
Range = Sheet.getDataRange();
Data = Range.getValues();
WR = Data[30][15];
}
Any help will be appriciated, Thanks.
Instead of doing [30][15], use this code to limit the range to one cell.
If that doesn't work, maybe your cell actually contains this DIV/0 value?
function readData(){
var Keys = "1Vp_fjFVFXHDjJRXl7C6mNzCK66jVB1I1BjieaZK6P";
var SheetName = "AAL";
var WR;
SS = SpreadsheetApp.openById(Keys);
Sheet = SS.getSheetByName(SheetName);
Range = Sheet.getRange(30, 15); //changed here
Data = Range.getValue(); //and here
WR = Data; //and here
}
I have looked at various solutions posted i.e. parsing, substrings and splitting and none of them either produce a value or the required value.
The format received via Salesforce API is "2014-08-19T02:26:00.000+0000"
Essentially I would like a custom function that can be used within Google Sheets to convert this date/time format and take daylight saving into consideration
Thank you beforehand
I use a simple function like below :
function parseDate(string) {
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
var t = parts[1].split(':');
var refStr = new Date(new Date(parts[0])).toString();// use this to get TZ for daylight savings
var fus = Number(refStr.substr(refStr.indexOf('GMT')+4,2));
return new Date(new Date(parts[0]).setHours(+t[0]+fus,+t[1],0));
}
firstly thank you for everyone's input. By using a combination of the info provided by RobG and Serge insas I revised the script and created one that suited my needs. Please see below, any further advice would be welcome.
/*
The script first has all variables declared.
As the script runs inconjunction with an API query running off single trigger for defined sequential functions where the previous parsed date records are cleared and then re-parsed and runs with loop function for a whole column of data within specified range
*/
function parseDate() {
var source_spreadsheet = SpreadsheetApp.openById("Sheet_Id");
SpreadsheetApp.setActiveSpreadsheet(source_spreadsheet);
var sheet = source_spreadsheet.getSheetByName("Sheet_Tab");
var startRow = 2;
var numRows = 4500;
var startCol = 1;
var numCols = 7;
var dataRange = sheet.getRange(startRow, startCol, numRows, numCols)
sheet.getRange(startRow, startCol + 1, numRows, numCols - 1).clear({contentsOnly: true});
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var SFConnectDate = row[0];
var DConnected = row[1];
var SFCutoverDate = row[2];
var DInUse = row[3];
var Lat = row[5];
var Long = row[6];
if (SFConnectDate != "" && DConnected == "" && Lat != "" && Long != "") {
var parts = SFConnectDate.split('T');
parts[0] = parts[0].replace(/-/g, '/');
var Fdd = parts[0].split('/');
var AllTime = parts[1].split('.');
var Ftt = AllTime[0].split(':');
var D = new Date(Fdd[0],(Fdd[1]-1),Fdd[2] ,Ftt[0],Ftt[1],Ftt[2]);
var TZ = (D.getTimezoneOffset())/60;
var DConnected = new Date(Fdd[0],(Fdd[1]-1),Fdd[2],(Ftt[0]-TZ),Ftt[1],Ftt[2]);
sheet.getRange(startRow + i, 2).setValue(DConnected);
}
}
}
I have some google spreadsheet logbook where I store duration of some activities in hours format [[HH]:MM:SS]. The spreadsheet adds such cells with no issues. However when I try to add them via Google Script I get some garbage. What I found is that Date() object is implicitly created for such cells, but I cannot find API of that value type.
I know I can convert the data to "hour integers" by multiplying them by 24 but that is a nasty workaround as it demands duplication of many cells. I would rather like a solution that will allow to do that in google script itself.
here is a working function that does the trick.
I first tried to format it as a date but 36 hours is not really standard !! so I did a little bit of math :-) )
To get it working you should set a cell somewhere with value 00:00:00 that we will use as a reference date in spreadsheet standard. in my code it is cell D1(see comment in code, reference date in SS is in 1900 and in Javascript is in 1970 ... that's why it is a negative constant of 70 years in milliseconds...)
here is the code and below a screen capture of the test sheet + the logger
It would be a good idea to modify this code to make it a function that takes cell value as parameter and returns the result as an array for example ([h,m,s] or something similar), this code is only to show how it works.
function addHoursValues() {
var sh = SpreadsheetApp.getActive()
var hours1 = sh.getRange('A1').getValue();
var hours2 = sh.getRange('B1').getValue();
var ref = sh.getRange('D1').getValue().getTime();
//var ref = -2209161600000 // you could also use this but it would be less obvious what it really does ;-)
Logger.log(ref+' = ref');
var h1 = parseInt((hours1.getTime()/3600000)-ref/3600000);
var h2 = parseInt((hours2.getTime()/3600000)-ref/3600000);
Logger.log(h1+' + '+h2+' = '+(h1+h2))
var m1 = parseInt((hours1.getTime()-h1*3600000-ref)/60000);
var m2 = parseInt((hours2.getTime()-h2*3600000-ref)/60000);
Logger.log(m1+' + '+m2+' = '+(m1+m2))
var s1 = parseInt((hours1.getTime()-h1*3600000-m1*60000-ref)/1000);
var s2 = parseInt((hours2.getTime()-h2*3600000-m2*60000-ref)/1000);
Logger.log(s1+' + '+s2+' = '+(s1+s2))
var ts=s1+s2
var tm=m1+m2
var th=h1+h2
if(ts>59){ts=ts-60;tm++};
if(tm>59){tm=tm-60;th++}
Logger.log('sum = '+th+':'+tm+':'+ts)
}
EDIT : here are 2 "function" versions with corresponding test functions that show how to use it
function getHMS(hrs) {
var t = hrs.getTime()/1000;
var ref = -2209161600;
var h = parseInt((t-ref)/3600);
var m = parseInt((t-h*3600-ref)/60);
var s = parseInt(t-h*3600-m*60-ref);
return[h,m,s];// returns an array of 3 discrete values
}
function testHMS(){
var sh = SpreadsheetApp.getActive();
var hours1 = sh.getRange('A1').getValue();
var hours2 = sh.getRange('B1').getValue();
var sumS = getHMS(hours1)[2]+getHMS(hours2)[2];// add seconds
var sumM = getHMS(hours1)[1]+getHMS(hours2)[1];// add minutes
var sumH = getHMS(hours1)[0]+getHMS(hours2)[0];// add hours
if(sumS>59){sumS=sumS-60 ; sumM++}; // handles values >59
if(sumM>59){sumM=sumM-60 ; sumH++}; // handles values >59
Logger.log(sumH+':'+sumM+':'+sumS);
}
OR
function addHMS(hrs1,hrs2) {
var t1 = hrs1.getTime()/1000;
var t2 = hrs2.getTime()/1000;
var ref = -2209161600;
var h = parseInt((t1-ref)/3600)+parseInt((t2-ref)/3600);
var m = parseInt((t1-parseInt((t1-ref)/3600)*3600-ref)/60)+parseInt((t2-parseInt((t2-ref)/3600)*3600-ref)/60);
var s = parseInt(t1-parseInt((t1-ref)/3600)*3600-parseInt((t1-parseInt((t1-ref)/3600)*3600-ref)/60)*60-ref)
+parseInt(t2-parseInt((t2-ref)/3600)*3600-parseInt((t2-parseInt((t2-ref)/3600)*3600-ref)/60)*60-ref);
if(s>59){s=s-60 ; m++}; // handles values >59
if(m>59){m=m-60 ; h++}; // handles values >59
return[h,m,s];// returns sum in an array of 3 discrete values
}
function othertestHMS(){
var sh = SpreadsheetApp.getActive();
var hours1 = sh.getRange('A1').getValue();
var hours2 = sh.getRange('B1').getValue();
Logger.log(addHMS(hours1,hours2));
}