Sheet JS using spaces in excel file headers - javascript

I'm using SheetJS to parse out an externally linked excel spreadsheet and create some HTML elements.
Overall, the way that I have it set up is fine, but I noticed that if the excel sheet that I'm referencing has spaces in the header (e.g. - First Name, Last Name, etc.) it won't recognize that and errors out. And I'm not sure how to go about accommodating the spaces in the headers.
Here's what I have:
Excel File Data:
JS:
var url = "https://assets.codepen.io/8689/test2.xlsx";
/* set up XMLHttpRequest */
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, { type: "binary" });
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
var jData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
$.each(jData, function (i, f) {
var el =
"<div class='thing'>" +
"<h2>" +
f.First Name +
" " +
f.Last Name +
"</h2>" +
"<h3>" +
f.Title +
"</h3>" +
"<p>" +
f.Comment +
"</p>" +
"</div>";
$(el).appendTo("#wrapper");
});
console.log(jData);
};
oReq.send();
I know that f.First Name and f.Last Name will error out, and I'm not sure what I can do to try and get it to accommodate the space. I tried an underscore, but that obviously doesn't work either (I kind of figured, but I wanted to test to be sure).

Ok, I did some more digging and I realized that since this is JSON data that is being parsed, I can use bracket notation to help parse that out:
$.each(jData, function (i, f) {
var el =
"<div class='thing'>" +
"<h2>" +
f["First Name"] +
" " +
f["Last Name"] +
"</h2>" +
"<h3>" +
f.Title +
"</h3>" +
"<p>" +
f.Comment +
"</p>" +
"</div>";
});

Related

How to hide the console when using app.system(...) in ExtendScript ? (Photoshop)

Everything is in the question. I just want to execute another process from a Photoshop Script (coded in ExtendScript) without the console appearing, or at least finding a way to put back in the front the Photoshop application.
Thx for your help !
function Main()
{
if (app.documents.length == 0)
{
return;
}
var tmpFolder = $.getenv("TEMP");
var exeFile = "convertor.exe";
/** Save a temporary copy of the current document. **/
var tmpPng = new File(tmpFolder + "\\" + app.activeDocument.name + ".png");
var saveOpts = new PNGSaveOptions;
app.activeDocument.saveAs(tmpPng, saveOpts, true, Extension.LOWERCASE);
/** Convert the file to a MP4 video. **/
var tmpMp4 = new File(tmpFolder + "\\" + app.activeDocument.name + ".mp4");
var conversionLog = new File(logFolder + "\\" + "conversion.log");
var command = exeFile + " -inputPng=\"" + tmpPng.fsName + "\" -outputMp4=\"\" -logPath=\"" + conversionLog.fsName + "\"";
app.system(command);
tmpPng.remove();
}
Main();

Update XML string with jQuery

I'm new to javascript and jQuery. I'm trying to get an XML string, update the value of one of the elements and get the new XML.
var header = "<RECORDS>" +
"<USERDATA>" +
"<USERID>ABC</USERID>" +
"<UTEMPLATE>NEWLOAN</UTEMPLATE>" +
"<FILEID></FILEID>" +
"<ENTITY>DW</ENTITY>" +
"</USERDATA>" +
"</RECORDS>";
var fileID = "XXXXXXXXXXXXXXX";
var xDoc = $.parseXML(header);
var $xml = $(xDoc);
var $elmFileID = $xml.find("FILEID");
$elmFileID.text(fileID);
This is what I have so for from examples I've seen but I don't know if it's right or what to do next.
What I want is a resulting string(either the existing header var or even a new var) with the content of the FILEID element as "XXXXXXXXXXXXXXX". Eventually that string will come from a service.
You can use it this way:
var header = "<RECORDS>" +
"<USERDATA>" +
"<USERID>ABC</USERID>" +
"<UTEMPLATE>NEWLOAN</UTEMPLATE>" +
"<FILEID></FILEID>" +
"<ENTITY>DW</ENTITY>" +
"</USERDATA>" +
"</RECORDS>";
var fileID = "XXXXXXXXXXXXXXX";
/* Convert Text to XML Object */
var xDoc = $.parseXML(header);
/* Change the fields required */
$(xDoc).find('FILEID').text(fileID)
/* Back to Text */
var newHeader = (new XMLSerializer()).serializeToString(xDoc);
/* Show changed XML */
console.log(newHeader);
You can use an XMLSerializer, with a fallback to the .xml property if XMLSerializer is not available (e.g. in older versions of IE):
function xmlToString(xmlData) {
if (window.XMLSerializer){
return (new XMLSerializer()).serializeToString(xmlData);
}
return xmlData.xml;
}
var header = "<RECORDS>" +
"<USERDATA>" +
"<USERID>ABC</USERID>" +
"<UTEMPLATE>NEWLOAN</UTEMPLATE>" +
"<FILEID></FILEID>" +
"<ENTITY>DW</ENTITY>" +
"</USERDATA>" +
"</RECORDS>";
var fileID = "XXXXXXXXXXXXXXX";
var xDoc = $.parseXML(header);
var $xml = $(xDoc);
var $elmFileID = $xml.find("FILEID");
$elmFileID.text(fileID);
console.log(xmlToString(xDoc));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Setting and retrieving cookies in javascript

So i am learning Javascript and trying to set and retrieve a cookie, my code all looks to be ok but there is obviously a problem here.
function init()
{
var panel = document.getElementById("panel");
var user = escape("Dan, 000456");
var expiry = new Date();
expiry.setTime(expiry.getTime() + (7*24*60*1000) );
document.cookie = "myData=" + user + ";" + "expires=" + expiry.toGMTString() + ";";
if (document.cookie)
{
var cookieString = unescape(document.cookie);
var list = cookieString.split("=");
if (list[0] === "myData")
{
var data = list[1].split(",");
var userName = data[0];
var userAcct = data[1];
}
}
panel.innerHTML += "Cookie String:" + cookieString;
panel.innerHTML += "<br>Split List:" + list;
panel.innerHTML += "<br>User Name:" + userName;
panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);
When I look in the results they are not what I am expecting to see:
Cookie String:undefined
Split List:undefined
User Name:undefined
User Account:undefined
Your main issue is now that you have corrected your syntax errors is that the following line:
var user = escape("Dan, 000456");
note: I believe the escape function is now deprecated?
change your javascript to this and make sure your browser allows cookies:
function init(){
var panel = document.getElementById("panel");
var user = ["Dan, 000456"]; //<--change #1
var expiry = new Date();
expiry.setTime(expiry.getTime() + (7*24*60*1000) );
//change #2 below added the array index of user to set the cookie value for myData
document.cookie = "myData=" + user[0] + ";" + "expires=" + expiry.toGMTString();
if (document.cookie)
{
var cookieString = unescape(document.cookie);
var list = cookieString.split("=");
if (list[0] === "myData")
{
var data = list[1].split(",");
var userName = data[0];
var userAcct = data[1];
}
}
panel.innerHTML += "Cookie String:" + cookieString;
panel.innerHTML += "<br>Split List:" + list;
panel.innerHTML += "<br>User Name:" + userName;
panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);
Also make sure your html looks like this:
<div id="panel">Test</div>
You can remove the Test from the div in the html above if you want. The Test value should be replaced by values in your panel.innerHTML assignments.

Kendo UI Grid Export CSV using Javascript

please help me my probs,am using kendo ui grid in my webapp & trying to grid data export into EXcel and CSV format. Code Works good in Chrome and files are downloading, but in Fire Fox its open a new window show the grid details in url and says bad request,
//code is
$("#exportcsv").click(function (e) {
debugger
var dataSource = $("#grid").data("kendoGrid").dataSource;
var filteredDataSource = new kendo.data.DataSource({
data: dataSource.data(),
filter: dataSource.filter()
});
filteredDataSource.read();
var data = filteredDataSource.view();
//start with the desired column headers here
var result = "\"ID\",\"EID\",\"Name\",\"Company Name\",\"Salary\",\"DID\",\"Date Of Join\"";
//each column will need to be called using the field name in the data source
for (var i = 0; i < data.length; i++) {
result += "\n";
result += "\"" + data[i].id + "\",";
result += "\"" + data[i].EID + "\",";
result += "\"" + data[i].EName + "\",";
result += "\"" + data[i].CName + "\",";
result += "\"" + data[i].Salary + "\",";
result += "\"" + data[i].DID + "\",";
result += "\"" + data[i].DOJ + "\",";
}
if (window.navigator.msSaveBlob) {
//Internet Explorer
window.navigator.msSaveBlob(new Blob([result]), 'ExportedKendoGrid.csv');
}
else if (window.webkitURL != null) {
//Google Chrome and Mozilla Firefox
var a = document.createElement('a');
result = encodeURIComponent(result);
a.href = 'data:application/csv;charset=UTF-8,' + result;
a.download = 'ExportedKendoGrid.csv';
a.click();
}
else {
//Everything Else
window.open(result);
}
e.preventDefault();
});
//below code is not working in firefox browser else if
(window.webkitURL != null) {
//Google Chrome and Mozilla Firefox
var a = document.createElement('a');
result = encodeURIComponent(result);
a.href = 'data:application/csv;charset=UTF-8,' + result;
a.download = 'ExportedKendoGrid.csv';
a.click();
}

Generating a CSV with JavaScript works but I am getting an empty trailing column

I've written some scripts to convert the pagination (20 photos per ajax request) from instagram json feeds to csv for easily storing the photo urls in our database. Our CMS is automatically able to convert CSV files into SQl files either by replacing the table or by appending to it. The problem is it will only work if ALL of the columns are the same.
It's close to totally working but I can't import my generated csvs because they keep getting an empty column where it should be line breaking to a new row because the final CSV output contains a comma + line break when it should only be returning the line break (i.e. without a trailing comma).
Encoding is UTF-8 and line breaks are being added using "\n". I've tried console logging just about every step of the process and it seems that there that
Here's a picture of one of the CSVs I am generating: http://screencast.com/t/dZfqN08A
Below is all the relevant code:
First I'm using ajax with a jsonp callback to load instagram photos based on a hashtag.
Photos are loaded like this:
function loadNext(nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
console.log('loadmore');
if (object) {
console.log(object);
$('.loadmore').fadeOut(500);
// chargement photos gallerie
$.each( object.data, function(home, photo) {
photo = '<div class="photo photo-load">' +
'<img class="pull-me" src="' + photo.images.low_resolution.url + '" height="380px" width="380px" alt="photo">' +
'<div class="dot"></div>' +
'<div class="share" >' +
'<!-- AddThis Button BEGIN -->' +
'<div class="addthis_toolbox addthis_default_style addthis_16x16_style">' +
'<a class="addthis_button_twitter"></a>' +
'<a class="addthis_button_facebook"></a>' +
'</div>' +
'<!-- AddThis Button END -->' +
'</div>' +
'<div class="text-photo">' +
'<div class="svg line w-line"></div>' +
'<h4 class="left">'+ photo.user.username + '</h4>' +
'<h4 class="right share-photo">PARTAGE</h4>' +
'</div>' +
'<div class="vote w-path-hover">' +
'<div class="fb-like" data-href="http://dev.kngfu.com/maurice/" data-layout="box_count" data-action="like" data-show-faces="false" data-share="false"></div>' +
'<div class="insta-like">' +
'<div class="count-box">' +
'<p>'+ photo.likes.count + '</p>' +
'</div>' +
'<a class="insta-button" title="Pour appuyer votre proposition préférée, rendez-vous sur Instagram." href="http://instagram.com/" ><i class="fa fa-instagram"></i>J aime</a>' +
'</div> ' +
'<div class="w-path"></div>' +
'<div class="base-cross"></div>' +
'<h4 class="vote-button">VOTE</h4>' +
'</div>' +
'</div>';
$(photo).appendTo( $( ".gallery" ) );
});
url = object.pagination.next_url;
console.log(url);
} else {
console.log("error");
}
} // end success func.
});
}
Then in a separate ajax call I can convert the same json feed to a csv file using this function (this function also calls a couple other functions so the dependent functions are included below the ajax call):
function convertJSON (nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
if (object) {
console.log(object);
var fromJSON = new Array();
i = 0;
$.each( object.data, function(home, photo) {
i++;
var photopath = photo.images.low_resolution.url;
var postID = photo.id;
var userID = photo.user.id;
var user = photo.user.username;
// watch out for those wild fullnames in instagram json
var fullname = photo.user.full_name;
fullname = fullname.replace(/[^a-z0-9]+|\s+/gmi, " ");
//console.log(fullname);
var likes = photo.likes.count;
var winner = 0;
var winnerplace = " ";
var campaign = "maurice1";
var timestamp = photo.created_time;
// easydate field formatting
var date = new Date();
date.setSeconds( timestamp );
var photodeleted = 0;
// add new rows to csv
var linebreak = "\n";
var arrayFromJSON = new Array( linebreak+photopath,
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join();
});
//url = object.pagination.next_url;
//console.log(url);
//console.log( fromJSON );
makeCSV( fromJSON );
} else {
console.log("error");
}
} // end success func.
});
}
// json to csv converter
function makeCSV (JSONData) {
//console.log("makeCSV() function was started");
var data = encodeURIComponent(JSONData);
var currentTime = new Date().getTime();
var date = getDate( currentTime );
//console.log(JSONData);
var fileName = date;
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ data; // finally append our URI encoded data
console.log(uri);
// generate a temp <a /> tag that will auto start our download when the function is called
var link = document.createElement("a");
link.id = new Date().getTime();
link.href = uri;
// link visibility hidden
link.style = "visibility:hidden";
link.download = fileName + ".csv";
// append anchor tag and click
$("div#hidden").append(link);
link.click();
//document.body.removeChild(link);
}
// this function just makes human readable dates for CSV filename and id of our link tag
function getDate() {
var date = new Date();
//zero-pad a single zero if needed
var zp = function (val){
return (val <= 9 ? '0' + val : '' + val);
}
//zero-pad up to two zeroes if needed
var zp2 = function(val){
return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
}
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
var h = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
var ms = date.getMilliseconds();
return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + 'h' + zp(min) + 'm' + zp(s) + 's';
}
From all the console logging I've done, I can definitely assure you that I'm getting no trailing comma until the final step where the json array data gets URI encoded.
Since this extra column is also included in the header row I'm wondering if it has to do with this line?
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
I've also tried ISO-8859-1 encoding but I get the same result.
Does anyone know why this is happening? Any help would be appreciated
Your passing an array of lines to encodeURIComponent. That will stringify the array, joining it with a comma - which you don't want.
What you should do is
var arrayFromJSON = new Array( photopath,
// remove linebreak here ^
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join(",");
// make comma explicit: ^^^
…
makeCSV( fromJSON );
…
var data = encodeURIComponent(JSONData.join("\n"));
// join the lines by a linebreak: ^^^^
…
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ "\n"
// ^^^^^^ add linebreak
+ data; // finally append our URI encoded data

Categories

Resources