I am trying to figure out if there is any way I can download a csv file onClick of the EXPORT button on my webpage using react.
Here's what I have under ponent right now -
<div>
<Button variant="contained"
size="small"
onClick={this.handleExport}>
<SaveIcon label="Export" />
Export
</Button>
</div>
where handleExport generates a csv file using JSON data from backend.
I have tried to use react-csv, react-csv-downloader packages but none of them work for me.
Is there any way I can download the csv file onClick? Sample code would be greatly appreciated.
Thanks!
I am trying to figure out if there is any way I can download a csv file onClick of the EXPORT button on my webpage using react.
Here's what I have under ponent right now -
<div>
<Button variant="contained"
size="small"
onClick={this.handleExport}>
<SaveIcon label="Export" />
Export
</Button>
</div>
where handleExport generates a csv file using JSON data from backend.
I have tried to use react-csv, react-csv-downloader packages but none of them work for me.
Is there any way I can download the csv file onClick? Sample code would be greatly appreciated.
Thanks!
Share Improve this question edited Jul 4, 2019 at 20:36 csmasterjk asked Jul 4, 2019 at 18:41 csmasterjkcsmasterjk 352 silver badges5 bronze badges 2- why the language tag spam? – Patrick Artner Commented Jul 4, 2019 at 18:42
- The tags you have been using are not appropriate for this question. Please take the tour, review what are tags and how should I use them? and edit your post. Remember to at least read the mouseover on the tags you are using when asking a question. – Patrick Artner Commented Jul 4, 2019 at 18:43
1 Answer
Reset to default 8I have this logic implemented. Code is very self explanatory.
export function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers)
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items)
var csv = convertToCSV(jsonObject)
var exportedFilename = fileTitle + '.csv' || 'export.csv'
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilename)
} else {
var link = document.createElement('a')
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob)
link.setAttribute('href', url)
link.setAttribute('download', exportedFilename)
link.style.visibility = 'hidden'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
}