Hello,
Using the default template, am I able to export the table as a CSV? Is there built-in functionality, or are there 3rd party libraries that you're aware of that could support this?
Thanks
```{javascript}
export function encode(data, columns) {
let csv = [];
if (data && data.length && columns && columns.length) {
let headers = [];
for (var i = 0; i < columns.length; i++) {
let column = columns[i];
let {header} = column;
if (header && header instanceof String) {
header = header.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/mg, "\\r").replace(/\n/mg, "\\n").replace(/\t/mg, "\\t") + '"';
}
headers.push(header);
}
csv.push(headers.join(','));
for (var i = 0; i < data.length; i++) {
let obj = data[i];
let row = [];
for (var j = 0; j < columns.length; j++) {
let column = columns[j];
let {accessor, cast} = column;
let cell = obj[accessor];
if (cast === 'string') {
cell = '"' + cell.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/mg, "\\r").replace(/\n/mg, "\\n").replace(/\t/mg, "\\t") + '"';
} else if (cast === 'time') {
cell = formatTime(cell)
} else if (cast === 'date') {
cell = moment(cell).utc().format('YYYY-MM-DD')
}
row.push(cell);
}
csv.push(row.join(','));
}
}
return csv.join("\n");
}
export function downloadCsv(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {type: "text/csv"});
downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
export function exportTableToCSV(data, columns, filename) {
let csv = encode(data, columns);
downloadCsv(csv, filename);
}
```
Note: It only works on chrome
That is one way to export, and there are technically unlimited ways to do so. The easiest way I imagine would be to use a ref to obtain the table instance, then use instance.getResolvedState().resolvedData and any csv creation tool (there are so many now) to parse the object into your desired format. In the end, React-Table does not have plans to include features like this as built-ins, but rather provide the appropriate API to integrate with other libraries with this capability. :)
For more questions on how to implement this, please join the Slack Channel :)
Most helpful comment
That is one way to export, and there are technically unlimited ways to do so. The easiest way I imagine would be to use a
refto obtain the table instance, then useinstance.getResolvedState().resolvedDataand any csv creation tool (there are so many now) to parse the object into your desired format. In the end, React-Table does not have plans to include features like this as built-ins, but rather provide the appropriate API to integrate with other libraries with this capability. :)