ste.co_
ste.co_

Reputation: 83

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

Upvotes: 8

Views: 19398

Answers (4)

benshabatnoam
benshabatnoam

Reputation: 7650

You can replace your Table mui component with Data Grid mui component which has an export func out of the box. This way you don't need to use another 3rd party library.

Upvotes: 0

arun-r
arun-r

Reputation: 3381

You can export all the data using exportAllData: true , no need filefy

<MaterialTable
              columns={
                  columns}
                  data={data}
                  title="Export all"
          
            options={{
            exportButton: true,
            exportAllData: true
            }} >

Upvotes: 0

wal
wal

Reputation: 17749

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

Upvotes: 3

bArmageddon
bArmageddon

Reputation: 8578

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.

Upvotes: 3

Related Questions