2

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.

1 Answer 1

8

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks worked for me! Didn't use the regex because I used the accept attribute in the input tag. Again thanks for the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.