javascriptreactjsfilereadersheetjs

Writing a function in javascript for converting uploaded excel sheet data to json


I am working on a MERN project whic require uploading of excel sheets and converting their data to JSON for rendering in tables. I am using xlsx react library. For this purupose i have written a function in javascript which is to be called in other components to get the desired result. However i get the result as undefined.

import * as XLSX from 'xlsx'

const excelSheetUpload = (file) =>{
    const fileType = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"]
    let selectedFile = file[0]   
    let reader = new FileReader();
    reader.readAsArrayBuffer(selectedFile)
    reader.onload = (e) => {
    const workbook = XLSX.read(e.target.result, {type:'buffer' });
    const worksheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[worksheetName];
    const data = XLSX.utils.sheet_to_json(worksheet);
    return data;
  }
}

export default excelSheetUpload;

When i use the above function in the react component giving the input to function as excelSheetUpload(event.target.files), i get undefined. May be some error in the javascript function.


Solution

  • Your excelSheetUpload method will return immediately, and after that onload will be called. Thats why you are getting undefined.

    You can create a react state and update that state when onload gives the data. Monitor that state with useEffect and do convert the data to json after getting the data.

    OR

    you can pass a callback function to excelSheetUpload and call that function on onload trigger.

    const excelSheetUpload = (file, callback) =>{
        const fileType = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"]
        let selectedFile = file[0]   
        let reader = new FileReader();
        reader.readAsArrayBuffer(selectedFile)
        reader.onload = () => {
            const workbook = XLSX.read(reader.result, {type:'buffer' });
            const worksheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[worksheetName];
            const data = XLSX.utils.sheet_to_json(worksheet);
            callback(data);
        }
    }