All files / src/lib/excel ExcelUpload.jsx

0% Statements 0/21
0% Branches 0/14
0% Functions 0/5
0% Lines 0/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                       
import React, { useState } from "react";
import ExcelJS from "exceljs";
 
const ExcelUploader = () => {
    const [data, setData] = useState([]);
 
    const handleFileUpload = async (event) => {
        const file = event.target.files[0];
        if (!file) return;
 
        const workbook = new ExcelJS.Workbook();
        const reader = new FileReader();
 
        reader.onload = async (e) => {
            const buffer = e.target.result;
            await workbook.xlsx.load(buffer);
 
            const worksheet = workbook.worksheets[0]; // data is in the first sheet
            const jsonData = [];
 
            worksheet.eachRow((row, rowNumber) => {
                if (rowNumber === 1) return; // skip header row
                jsonData.push({
                    _id: rowNumber - 2,
                    first_name: row.getCell(1).value || "",
                    middle_name: row.getCell(2).value || "",
                    last_name: row.getCell(3).value || "",
                    email: row.getCell(4).value || "",
                    role: row.getCell(5).value || "teacher",
                });
            });
 
            setData((prevData) => [...prevData, ...jsonData]);
        };
 
        reader.readAsArrayBuffer(file);
    };
 
    return (
        <div>
            <h2>Upload Excel File</h2>
            <input type="file" accept=".xlsx, .xls" onChange={handleFileUpload} />
            <div>
                <h3>Uploaded Data</h3>
                <pre>{JSON.stringify(data, null, 4)}</pre>
            </div>
        </div>
    );
};
 
export default ExcelUploader;