Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading excel file in react

I am trying to read excel file and to convert it to JSON format using XLSX but not able to do it. Can any one suggest method for conversion when file is on local machine.

like image 474
Jashan Chahal Avatar asked Jan 18 '26 20:01

Jashan Chahal


1 Answers

Choose your local machine excel sheet by input. After that,
your Excel data will show as JSON string.

function Upload() {
    const fileUpload = (document.getElementById('fileUpload'));
    const regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$/;
    if (regex.test(fileUpload.value.toLowerCase())) {
        let fileName = fileUpload.files[0].name;
        if (typeof (FileReader) !== 'undefined') {
            const reader = new FileReader();
            if (reader.readAsBinaryString) {
                reader.onload = (e) => {
                    processExcel(reader.result);
                };
                reader.readAsBinaryString(fileUpload.files[0]);
            }
        } else {
            console.log("This browser does not support HTML5.");
        }
    } else {
        console.log("Please upload a valid Excel file.");
    }
}

function processExcel(data) {
    const workbook = XLSX.read(data, {type: 'binary'});
    const firstSheet = workbook.SheetNames[0];
    const excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);

    console.log(excelRows);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Process Excel File</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.0/xlsx.full.min.js"></script>
</head>
<body>
<input class="upload-excel" type="file" id="fileUpload" onchange="Upload()"/>
</body>
</html>
like image 121
lakshitha madushan Avatar answered Jan 20 '26 11:01

lakshitha madushan