Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can export material-ui table to CSV?

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

like image 215
ste.co_ Avatar asked Oct 16 '22 10:10

ste.co_


2 Answers

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.

like image 133
bArmageddon Avatar answered Oct 21 '22 01:10

bArmageddon


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

like image 32
wal Avatar answered Oct 21 '22 00:10

wal