Skip to content

Instantly share code, notes, and snippets.

@evangrim
Last active May 10, 2022 05:12
Show Gist options
  • Save evangrim/34caf2ebd652106f3350d92417c23a12 to your computer and use it in GitHub Desktop.
Save evangrim/34caf2ebd652106f3350d92417c23a12 to your computer and use it in GitHub Desktop.
JavaScript create and download CSV
//columns is array of string values, or something falsy
//rows is 2d array with inner arrays comprised of cell values (strings)
//columns array will have same length as each member of rows array
$scope.downloadCsv = function(columns, rows, filenameWithoutExtension) {
let separator = "\n";
// join(',') + "\n";
// const header = columnsArr.join(',') + "\r\n";
const header = columns.join(',') + separator;
const body = rows.map(function(row) {
return row.join(',');
})
.join(separator);
const data = header + body;
// blob allows largest file size of available options, but limit varies by browser
const blob = new Blob([data], {type: 'text/csv'});
const url = window.URL.createObjectURL(blob);
// attach a hidden anchor to the dom and emit click event
// this technique is necessary for firefox
const a = document.createElement('a');
a.setAttribute('hidden','');
a.setAttribute('href', url);
a.setAttribute('download', filenameWithoutExtension + '.csv');
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment