someone of you can explain me how to export a material-ui-table to CSV file ?
<Paper>
<Table>
<TableHead>
<TableRow>
<TableCell>A</TableCell>
<TableCell >B</TableCell>
<TableCell>C</TableCell>
<TableCell>D</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.rows.map(row => {
return (
<TableRow key={row.ID}>
<TableCell>{row.A} </TableCell>
<TableCell >{row.B}</TableCell>
<TableCell>{row.C}</TableCell>
<TableCell >{row.D}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Paper>
I need to create a component that exports this table to csv format
On Material-UI's tables page 'Complementary projects' section they recommend on using material-table.
One of material-table's props is exportButton={true}
, which renders a CSV Export button.
If you want to roll your own solution you can use filefy
which is what material-table uses under the hood
npm i --save filefy
then
import { CsvBuilder } from 'filefy';
//...
const builder = new CsvBuilder('filename.csv');
builder
.setDelimeter(',')
.setColumns(['A', 'B', 'C', 'D' ])
.addRows(data)
.exportFile();
rows
is an array of arrays, e.g.
const rows = [
[ 'r1c1', 'r1c2', 'r1c3', 'r1c4'],
[ 'r2c1', 'r2c2', 'r2c3', 'r2c4'],
]
There is a bit of a disconnect here as a <TableCell>
can contain jsx inside of it (even tho it does not in your case) so you cannot simply 'dump' the data from the <Table>
as it may not be plain text.
If you have simple string values like in your case it may be suitable to define a string[][]
that can be used for both your jsx and CsvBuilder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With