Skip to content

Instantly share code, notes, and snippets.

@syntagmatic
Created March 26, 2012 03:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save syntagmatic/2202660 to your computer and use it in GitHub Desktop.
Save syntagmatic/2202660 to your computer and use it in GitHub Desktop.
Export CSV with Javascript
// assumes variable data, which is a homogenous collection of objects
// get keys
var keys = _.keys(data[0]);
// convert to csv string
var csv = keys.join(",");
_(data).each(function(row) {
csv += "\n";
csv += _(keys).map(function(k) {
return row[k];
}).join(",");
});
// trick browser into downloading file
var uriContent = "data:application/octet-stream," + encodeURIComponent(csv);
var myWindow = window.open(uriContent, "Nutrient CSV");
myWindow.focus();
@hjr3
Copy link

hjr3 commented Mar 15, 2013

Hmm, this does not seem RFC840 compliant and could cause errors. Consider for example if one of the keys has a newline in it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment