Skip to content

Instantly share code, notes, and snippets.

@hewersonfreitas
Forked from surjikal/csv.js
Created November 5, 2020 19:58
Show Gist options
  • Save hewersonfreitas/127e96432a3e4471e746ce4322a7ee22 to your computer and use it in GitHub Desktop.
Save hewersonfreitas/127e96432a3e4471e746ce4322a7ee22 to your computer and use it in GitHub Desktop.
Generating a downloadable CSV file in the browser.
// 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment