Skip to content

Instantly share code, notes, and snippets.

@surjikal
Forked from ghuntley/gist:5064790
Last active November 5, 2020 19:58
Show Gist options
  • Save surjikal/5115068 to your computer and use it in GitHub Desktop.
Save surjikal/5115068 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