Created
February 28, 2023 14:26
-
-
Save goish135/3a1310a1c646e4eaa72d78f23f41957a to your computer and use it in GitHub Desktop.
CSV Reader
This file contains 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
// npm install react-csv --save; | |
// npm install papaparse | |
import React, { useState } from "react"; | |
import { CSVLink } from "react-csv"; | |
import Papa from "papaparse"; | |
const App = () => { | |
const [tableRows, setTableRows] = useState([]); | |
//State to store the values | |
const [values, setValues] = useState([]); | |
const [parsedData, setParsedData] = useState([]); | |
const changeHandler = (event) => { | |
// Passing file data (event.target.files[0]) to parse using Papa.parse | |
Papa.parse(event.target.files[0], { | |
header: true, | |
skipEmptyLines: true, | |
complete: function (results) { | |
const rowsArray = []; | |
const valuesArray = []; | |
// Iterating data to get column name and their values | |
results.data.map((d) => { | |
rowsArray.push(Object.keys(d)); | |
valuesArray.push(Object.values(d)); | |
}); | |
console.log('export data:',results.data) | |
// Parsed Data Response in array format | |
setParsedData(results.data); | |
// Filtered Column Names | |
setTableRows(rowsArray[0]); | |
// Filtered Values | |
setValues(valuesArray); | |
}, | |
}); | |
}; | |
return ( | |
<div style={{ textAlign: "center" }}> | |
<h1>Import Export CSV</h1> | |
<form> | |
<button type="button" style={{ marginRight: "25px" }}> | |
<label htmlFor="formId"> | |
{/* <input name="" type="file" id="formId" hidden /> */} | |
<input | |
type="file" | |
name="file" | |
onChange={changeHandler} | |
accept=".csv" | |
// style={{ display: "block", margin: "10px auto" }} | |
id="formId" hidden | |
/> | |
Import CSV | |
</label> | |
</button> | |
{parsedData.length===0 ?<button type="button" disabled>Export CSV</button>: | |
<button> | |
<CSVLink | |
data={parsedData} | |
filename="export.csv" | |
style={{ textDecoration: "none", color: "black" }} | |
> | |
Export CSV | |
</CSVLink> | |
</button> | |
} | |
</form> | |
<br /> | |
<table style={{ margin: "auto" }}> | |
<thead> | |
<tr key={"header"}> | |
{tableRows.map((key) => ( | |
<th>{key}</th> | |
))} | |
</tr> | |
</thead> | |
<tbody> | |
{values.map((item) => ( | |
<tr key={item.id}> | |
{Object.values(item).map((val) => ( | |
<td>{val}</td> | |
))} | |
</tr> | |
))} | |
</tbody> | |
</table> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment