I have a web application that needs to be able to export some javascript data (arrays, mostly) to Microsoft Excel. I've been told the best way to do that is to save my data as a CSV file. I know there are a lot of threads that deal with similar issues, but so far I have not found exactly what I am looking for... I would like to get around calling a web service and do this through the client side.
Following some suggestions I tried writing my arrays to disk using data URIs. Here is the code that I have in javascript:
function exportToCsv() {
var data = [JSONdata.mass, JSONdata.waterMass, JSONdata.bedTemp, JSONdata.evapRate];
var keys = ["Mass(kg)", "H2O Mass in Bed(kg)", "Bed Temperature(kg)", "Evaporation Rate"];
var str;
var orderedData = [];
for (var i = 0, iLen = data.length; i < iLen; i++) {
temp = data[i];
for (var j = 0, jLen = temp.length; j < jLen; j++) {
if (!orderedData[j]) {
orderedData.push([temp[j]]);
} else {
orderedData[j].push(temp[j]);
}
}
}
str = keys.join(',') + '\r\n' + orderedData.join('\r\n');
var uri = 'data:application/csv;charset=UTF-8,' + str;
window.open(uri);
}
The string str
looks like its in CSV format, but when I save my file, it turns up empty.
I also would very much like to save the contents of str
to a CSV file from a pop-up prompt.
I looked into Downloadify and FileSaver.js, but had trouble finding good documentation. This seems like it should be a fairly easy thing to do... Please lend a hand!
Thanks in advance!
EDIT/UPDATE
I ended up getting my solution to work using FileSaver.js. My data was a header followed by four large double arrays, so CVS was a good enough format for me. Here is the code I used to get my CSV files to save properly:
function exportExcel()
{
var data = [JSONdata.mass, JSONdata.waterMass, JSONdata.bedTemp, JSONdata.evapRate];
//var data = [[1,2,3,4,5],[11,22,33,44,55],[111,222,333,444,555],[1111,2222,3333,4444,5555]];
var keys = ['"Mass(kg)"', '"H2O Mass in Bed(kg)"', '"Bed Temperature(kg)"', '"Evaporation Rate"'];
var convertToCSV = function(data, keys) {
var orderedData = [];
for (var i = 0, iLen = data.length; i < iLen; i++) {
temp = data[i];
for (var j = 0, jLen = temp.length; j < jLen; j++) {
quotes = ['"'+temp[j]+'"'];
if (!orderedData[j]) {
orderedData.push([quotes]);
} else {
orderedData[j].push(quotes);
}
}
}
return keys.join(',') + '\r\n' + orderedData.join('\r\n');
}
var str = convertToCSV(data, keys);
var blob = new Blob([str], {type: "text/plain;charset=utf-8"});
var filename = prompt("Please enter the filename");
if(filename!=null && filename!="")
saveAs(blob, [filename+'.csv']);
else
alert("please enter a filename!");
}
If anyone else comes across a similar issue, this solution worked pretty well for me and allowed me to skip going back to the server side. Thanks for the help everyone.