Skip to content

Instantly share code, notes, and snippets.

@mingrammer
Last active June 14, 2023 04:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mingrammer/2cc51f97d31a63bdea8c41c20234cadd to your computer and use it in GitHub Desktop.
Save mingrammer/2cc51f97d31a63bdea8c41c20234cadd to your computer and use it in GitHub Desktop.
Download CSV files directly from your browser
function createCSV(data) {
var lineDelimiter = '\n';
var csv = {
'title': '',
'head': '',
'body': ''
};
csv.title = 'csv-title.csv';
csv.head = '...'; // make your own csv head
csv.body = '...'; // make your own csv body with `lineDelimiter` (optional)
return csv;
}
function downloadCSV(csv) {
var csvContent = csv.head + csv.body;
if (!csvContent.match(/^data:text\/csv/i)) {
csvContent = 'data:text/csv;charset=utf-8,' + csvContent; // use 'data:text/csv;charset=utf-8,\ufeff', if you consider using the excel
}
var data = encodeURI(csvContent);
var link = document.createElement('a');
link.href = data;
link.download = csv.title;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
var csv = createCSV(data);
downloadCSV(csv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment