App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
import React, { useState } from "react"; import { Container, Form, Button, Table, Alert } from "react-bootstrap"; import Papa from "papaparse"; import "bootstrap/dist/css/bootstrap.min.css" const App = () => { const [csvData, setCsvData] = useState([]); const [headers, setHeaders] = useState([]); const [error, setError] = useState(""); const handleFileUpload = (e) => { const file = e.target.files[0]; if (!file) { setError("No file selected."); return; } if (file.type !== "text/csv") { setError("Please upload a valid CSV file."); return; } setError(""); Papa.parse(file, { header: true, skipEmptyLines: true, complete: (results) => { if (results.data.length === 0) { setError("The CSV file is empty."); } else { setHeaders(Object.keys(results.data[0])); setCsvData(results.data); } }, error: () => { setError("Error reading the CSV file."); }, }); }; return ( <Container className="my-4"> <h1 className="text-center">CSV File Viewer</h1> {/* File Upload */} <Form.Group controlId="csvFile" className="my-3"> <Form.Label>Upload a CSV File</Form.Label> <Form.Control type="file" accept=".csv" onChange={handleFileUpload} /> </Form.Group> {error && <Alert variant="danger">{error}</Alert>} {/* CSV Table */} {csvData.length > 0 && ( <Table striped bordered hover responsive className="mt-4"> <thead> <tr> {headers.map((header, index) => ( <th key={index}>{header}</th> ))} </tr> </thead> <tbody> {csvData.map((row, rowIndex) => ( <tr key={rowIndex}> {headers.map((header, colIndex) => ( <td key={colIndex}>{row[header]}</td> ))} </tr> ))} </tbody> </Table> )} </Container> ); }; export default App; |