Last active
November 28, 2024 12:12
-
-
Save mingrammer/2cc51f97d31a63bdea8c41c20234cadd to your computer and use it in GitHub Desktop.
Download CSV files directly from your browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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