This is a very much needed requirement in all most all web applications as and when backend doesn't support download for given results.
We generally populate results in table -> To populate we need to iterate over array contains data objects.
Like,
const data = [
{ name: 'Tom', id: '1234'},
{ name: 'James', id: '3456'},
{ name: 'Jerry', id: '7890'},
{ name: 'Peter', id: '4321'}
];
And, the above forms table as:
Just want same results to be downloaded as CSV.
const headers = Object.keys(data[0]).join();
const content = data.map(value => Object.values(value).join());
const csv = [headers].concat(content).join("\n");
const element = document.createElement('a');
element.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
element.target = '_blank';
element.download = 'export.csv';
element.click();
Done. Your CSV gets download as show in below:
Always welcome any improvements.
Thanks.
Top comments (0)