Created
June 1, 2019 14:00
-
-
Save CarlosDanielDev/5d272f2660ee2cb91171fd52d3fb7ad8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
export default class JsonToCsv extends React.Component{ | |
// função que faz Download do Arquivo .csv | |
download(data){ | |
const blob = new Blob([data], {type: 'text/csv'}) | |
// console.log(blob) | |
const url = URL.createObjectURL(blob) | |
const a = document.createElement('a') | |
a.setAttribute('hidden', '') | |
a.setAttribute('href', url) | |
a.setAttribute('download', `Download-${this.props.id}.csv`) | |
document.body.appendChild(a) | |
a.click() | |
document.body.removeChild(a) | |
} | |
//função que tranforma objeto em CSV | |
objectToCsv(data){ | |
const csvRows = []; | |
// get os Headers do Objeto | |
const headers = Object.keys(data[0]) | |
csvRows.push(headers.join(',')) | |
// loop nas rows do object | |
for (const row of data){ | |
const values = headers.map(header =>{ | |
// replace pra substituir ',' por '\' | |
const escaped = (''+row[header]).replace(/"/g, '\\"') | |
return `"${escaped}"` | |
}) | |
csvRows.push(values.join(',')) | |
} | |
return csvRows.join('\n') | |
} | |
// função Main, invoca a função objectToCsv que tranforma JSON em CSV | |
mainCsv(csv){ | |
return () =>{ | |
const csvData = this.objectToCsv(csv) | |
// console.log(csv) | |
this.download(csvData) | |
} | |
} | |
render(){ | |
return ( | |
<div> | |
{*/ aqui eu tenho um botão onde no onclick eu chamo uma função passando o objeto que eu quero converter em CSV/*} | |
<button className="btn buttonConsultar z-depth-2" onClick={this.mainCsv(csv)}> | |
<i className="fas fa-file-csv" ></i> | |
</button> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment