I have a Google Sheet where column 'A' is a date Time column. LINK
i converted this Google sheet file to JSON Data. Link
from this JSON data is fetching my website page in a table. Link
The Problem with date is it's showing 17/01/2023 19:47:35 To 2023-01-17T14:17:35.270Z
How can I make this Readable
My Apps Script Code is below
function doGet(e) {
var sheet = SpreadsheetApp.getActive();
var nse = sheet.getSheetByName("Sheet1");
var data = [];
var rlen = nse.getLastRow();
var clen = nse.getLastColumn();
var rows = nse.getRange (1,1, rlen, clen).getValues();
for(var i = 1; i < rows.length; i++) {
var datarow = rows[i];
var record = {};
for(var j=0; j < clen ; j++){
record[rows[0][j]] = datarow[j];
}
data.push(record);
}
var result = JSON.stringify(data);
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
}
and My Javascript code is here.
<section>
<h1>My Google Sheet Table</h1>
<!-- TABLE CONSTRUCTION-->
<table id='mytable'>
<!-- HEADING FORMATION -->
<tr>
<th>Date</th>
<th>Name</th>
<th>Phone Number</th>
<th>Months</th>
</tr>
<script>
$(document).ready(function () {
// FETCHING DATA FROM JSON FILE
$.getJSON("JsonDataLink",
function (data) {
var content = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
//CONSTRUCTION OF ROWS HAVING
// DATA FROM JSON OBJECT
content += '<tr>';
content += '<td>' +
value.DATE + '</td>';
content += '<td>' +
value.Name + '</td>';
content += '<td>' +
value.Phone + '</td>';
content += '<td>' +
value.Months + '</td>';
content += '</tr>';
});
//INSERTING ROWS INTO TABLE
$('#mytable').append(content);
});
});
</script>
</section>
</body>
</html>
When I saw your provided sample Spreadsheet, it seems that the values of the column "A" of "DATE" are the date object. In this case, how about modifying it as follows?
Pattern 1:
In this pattern, only Google Apps Script is modified.
IMPORTANT:
As an important point, in your provided sample Spreadsheet, there are 2 functions of doGet. In this case, the expected result might not be able to be obtained. So, please remove one of the 2 doGet functions and please modify it as follows.
Modified script:
function doGet(e) {
var sheet = SpreadsheetApp.getActive();
var nse = sheet.getSheetByName("Sheet1");
var data = [];
var rlen = nse.getLastRow();
var clen = nse.getLastColumn();
var rows = nse.getRange(1, 1, rlen, clen).getDisplayValues(); // Modified
for (var i = 1; i < rows.length; i++) {
var datarow = rows[i];
var record = {};
for (var j = 0; j < clen; j++) {
record[rows[0][j]] = datarow[j];
}
data.push(record);
}
var result = JSON.stringify(data);
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
}
Pattern 2:
In this pattern, only Google Apps Script is modified. In this modification, the date object retrieved by getValues is formatted.
From:
record[rows[0][j]] = datarow[j];
To:
record[rows[0][j]] = j == 0 ? Utilities.formatDate(datarow[j], Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm") : datarow[j];
Please modify the format for your actual situation.
Pattern 3:
In this pattern, only Javascript is modified. In this modification, moment.js is used. You can see it with as https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js of CDN.
Please modify your Javascript as follows.
From:
content += '<td>' +
value.DATE + '</td>';
To:
content += '<td>' +
moment(new Date(value.DATE)).format('YYYY-MM-DD HH:mm') + '</td>';
Please modify the format for your actual situation.
Note:
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
References:
getDisplayValues()
formatDate(date, timeZone, format)
moment.js
Related
The below code does as intended - except it ONLY copies the first 3 columns - and I need it to copy all the Data on the spreadsheet.I thought when the code says sheet.getDataRange(); that means all data but not in this case. Could I get a brief explanation of the issue rather than just the answer - love to know why 3 columns only are being selected.
function STCSV() {
var ss = SpreadsheetApp.openById("");
var sheets = ss.getSheets();
var sheet = sheets[3];
var formattedDate = Utilities.formatDate(new Date(), "GMT+10", "dd-MM-yyyy' '");
// append ".csv" extension to the sheet name
fileName = formattedDate + SpreadsheetApp.getActiveSpreadsheet().getName() + " ST CSV IMPORT " +
".csv";
var folder = DriveApp.getFolderById("");
// convert all available sheet data to csv format
var csvFile = convertRangeToCsvFile_(fileName, sheet);
// create a file in the Docs List with the given name and the csv data
var file = folder.createFile(fileName, csvFile);
}
function convertRangeToCsvFile_(csvFileName, sheet) {
// get available data range in the spreadsheet
var activeRange = sheet.getDataRange();
var data = activeRange.getValues();
var csvFile = undefined;
// loop through the data in the range and build a string with the csv data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// join each row's columns
// add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
Appreciate any help. Thanks
The getDataRange() method returns a range corresponding to the dimensions in which data is present; therefore, the sheet.getDataRange() does return all the data from the sheet.
The reason only 3 columns are selected is because your sheet actually has only 3 columns.
Reference
Sheet Class Apps Script - getDataRange().
I've pulled together the following script that successfully extracts a range of data from a Sheets workbook, puts it in a HMTL table, and emails that table to the recipient.
The only problem is that, try as I might, I cannot have the email display rounded numbers; they will show in excess of 15 decimal places. Is there a way to clean this up? I have tried a range of solutions, from numberformatting in Script and changing the cell display format in sheets. Nothing will work!
A screenshot of the output is below.
function SendEmail() {
// Fetch the ingredients
var ingredients = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var data = ingredients.getRange("F2:G11").getValues();
var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'
var htmltable = '<table ' + TABLEFORMAT +' ">';
for (row = 0; row<data.length; row++){
htmltable += '<tr>';
for (col = 0 ;col<data[row].length; col++){
if (data[row][col] === "" || 0) {htmltable += '<td>' + 'None' + '</td>';}
else
if (row === 0) {
htmltable += '<td>' + data[row][col] + '</td>';
}
else {htmltable += '<td>' + data[row][col] + '</td>';}
}
htmltable += '</tr>';
}
htmltable += '</table>';
Logger.log(data);
Logger.log(htmltable);
// Fetch the email address
var email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("E21");
var emailAddress = email.getValues();
// Fetch the date
var date = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("E24").getValues();
// Send Email
var message = {htmlBody: htmltable};
var subject = 'Ingredients - '+ date;
MailApp.sendEmail(emailAddress, subject, '', {htmlBody : htmltable});
}
The simplest way may be to use
.getDisplayValues() instead of .getValues().
So:
var data = ingredients.getRange("F2:G11").getDisplayValues();
This way you can format the data on the sheet as you like.
And the script will use the numbers as they appear on the sheet and not what their real values may be.
===========================
Your other options are to use Math.round(), Math.ceil() or Math.floor() functions in the loop when processing data[row][col].
I am trying to send an email contains a fixed message and below it a formatted HTML table which gets the range values only if the total column "row[23]" is not empty, which means he's on shift.
Simply I am trying to send the productivity to my team in a table containing the members in duty, in the Google Sheet formula to reflect the internal productivity, but I need the script to only contain the row with values in the table format, I've tried to create a new HTML page and link it with the .gs script, I've tried to use library, I've tried to generate formatted HTML table script using websites and combine them.
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet6')
var startRow = 1;
var numRows = sheet.getLastRow()
var dataRange = sheet.getRange('A2:x18' );
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = 'sherif.gamal1611#gmail.'
var message = "Hi team, kindly check our prod till now as below "
var Date= row[0];
var subject = 'Productivity Report' + " " + Date;
if (row[23] !="" ); {
//var htmltable =[];
var TABLEFORMAT = 'cellspacing="10" cellpadding="10" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:center;text-decoration:none;font-style:normal;'
var html table = '<table ' + TABLE FORMAT +' ">';
for (row = 0; row<data.length; row++){
htmltable += '<tr>';
for (col = 2 ;col<data[row].length; col++){
if (data[row][col] === "" || 0) {htmltable += '<td>' + '' + '</td>';}
else
if (row === 0) {
htmltable += '<th>' + data[row][col] + '</th>';
}
else {htmltable += '<td>' + data[row][col] + '</td>';}
}
htmltable += '</tr>';
}
htmltable += '</table>';
Logger.log(data);
Logger.log(htmltable);
MailApp.sendEmail(emailAddress, subject, message,{ htmlBody: htmltable});
SpreadsheetApp.flush();
}
}
The spacing and padding in the mail I receive is in a bad shape, I wonder if it's possible to be aligned and have the same format in the sheet and the mail to contain a message before the HTML table and the table to only contains the rows which has values in the total column row[23] " column X".
Make everything a table and then make the borders around your initial message clear
I'm new to App Script. I'm trying to read the submitted data using App Script. I tried to use the answer provided here, but I'm not able to read it.
I tried many other method, they are also not working.
function myFunction() {
var form = FormApp.openById('1_HABIBYRZ-zsEMuzMCnsrAOYFlQSKwaIhmeT1y2SY6Y');
var formResponses = form.getResponses();
MailApp.sendEmail ("test#appirio.com", "Form Submited: Foo feedback " + Date.now(), +formResponses);
}
I also want to know, how to debug any issue in App Script.
Thanks in Advance!
The other answer above may work, but it's a bit complicated. To let you keep the form responses as a variable inside your program, which would allow you to email it, you can do this:
function formResponsesToArray() {
var app = FormApp.openById(...),
responses = app.getResponses(), stringResponses = []
responses.forEach(function(r) {
var response = []
r.getItemResponses().forEach(function(i) {
response.push(i.getResponse())
})
stringResponses.push(response)
})
Logger.log(stringResponses)
}
Which will log an array of responses like this:
The way I'd recommend doing it is feed your form responses into a google sheet, and then export is as a csv via attachment in an email. like so below. It is important to make sure the correct API's are active, such as Drive API, Gmail API and that your oauthScopes are added to the manifest if need be.
editing my answer to recommend stewarts answer. much cleaner, simpler and way more efficient.
function ExportToCSVCrntMonth(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); //change this to sheet name
// Change the below line to get the folder where you want the CSV files stored.
var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_') + '_csv_' + new Date().getTime());
fileName = ss.getName() + ".csv";
var csvFile = convertRangeToCsvFileCrnt_(fileName, ss);
folder.createFile(fileName, csvFile);
var csvmail = folder.getFilesByName('your sheet name + .csv');
MailApp.sendEmail({
to: "your email ere",
subject: "CSV attached",
body: "body text",
attachments: [csvmail.next()]
});
}
function convertRangeToCsvFileCrnt_(csvFileName, ss) {
var activeRange = ss.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
I am trying to create a json of google spreadsheet in specific folder in google drive.
for example my google drive have folder named "temp" and it contains google spreadsheet i am then running google app script code from that spreadsheet.
here is the code
function exportSheetAsJSON()
{
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var output = "";
output += "{\""+sheet.getName()+"\" : {\n";
var header = values[0];
for (var i = 1; i < numRows; i++)
{
if (i > 1) output += " , \n";
var row = values[i];
output += "\""+row[0]+"\" : {";
for (var a = 1;a<numCols;a++)
{
if (a > 1) output += " , ";
output += "\""+header[a]+"\" : \""+row[a]+"\"";
}
output += "}";
//Logger.log(row);
}
output += "\n}}";
Logger.log(output);
DriveApp.createFile(sheet.getName()+".json", output, MimeType.PLAIN_TEXT);
};
above the code works perfectly but it always create json file in root folder of google drive instead of temp folder.
can anyone have solution for the above problem ?
Try this:
Logger.log(output);
var theFolder = DriveApp.getFoldersByName('temp');
while (theFolder.hasNext()) {
var folder = theFolder.next();
Logger.log(folder.getName());
folder.createFile(sheet.getName()+".json", output, MimeType.PLAIN_TEXT);
}
};