Reading excel file in Reactjs

70,333

Solution 1

I have successfully read excel file using Sheetjs's npm version xlsx.

Here is code:

import * as XLSX from 'xlsx';
//f = file
var name = f.name;
const reader = new FileReader();
reader.onload = (evt) => { // evt = on_file_select event
    /* Parse data */
    const bstr = evt.target.result;
    const wb = XLSX.read(bstr, {type:'binary'});
    /* Get first worksheet */
    const wsname = wb.SheetNames[0];
    const ws = wb.Sheets[wsname];
    /* Convert array of arrays */
    const data = XLSX.utils.sheet_to_csv(ws, {header:1});
    /* Update state */
    console.log("Data>>>"+data);
};
reader.readAsBinaryString(f);

Solution 2

Noman Ali! Thank you.
I used, this code

const handleUpload = (e) => {
    e.preventDefault();

    var files = e.target.files, f = files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        var data = e.target.result;
        let readedData = XLSX.read(data, {type: 'binary'});
        const wsname = readedData.SheetNames[0];
        const ws = readedData.Sheets[wsname];

        /* Convert array to json*/
        const dataParse = XLSX.utils.sheet_to_json(ws, {header:1});
        setFileUploaded(dataParse);
    };
    reader.readAsBinaryString(f)
}

Solution 3

I find xlsx to work pretty well. xlsx Package

Share:
70,333

Related videos on Youtube

Noman Ali
Author by

Noman Ali

BY DAY: I am a professional full stack web developer at an IT Company, and love to do creative front end and backend apps. BY NIGHT: I am a movie/drama lover. And play games whenever i get some extra time.

Updated on November 23, 2020

Comments

  • Noman Ali
    Noman Ali over 3 years

    I am trying and banging my head already while trying to read excel file in Reactjs.

    I have tried multiple libraries out there like, Sheetjs , excel-parser, exceljs and so on (like 8-9) libraries.

    I am getting weird and different errors in every library.

    For example i am using excel-parser and getting following error

    Module not found: 'child_process'
    

    That is because it is a node module and won't work in browser.

    Anyone know some good and easy library that can work with reactjs in browser?

  • Noman Ali
    Noman Ali over 6 years
    Could you please answer this then> stackoverflow.com/questions/46911079/…
  • steve
    steve over 5 years
    but i have a doubt in this. how to restrict the brows file should be only .xlsx format. Other files should allow to upload
  • RyanDay
    RyanDay about 5 years
    how are you getting the file? Do you have to use a require with excel-loader?
  • Miguel Luisillo
    Miguel Luisillo over 2 years
    Here is the repo demo for react github.com/SheetJS/sheetjs/tree/…
  • Konrad Grzyb
    Konrad Grzyb about 2 years
    For me there is a problem that if there is empty cell there is no column key and value in data at all and I expect to be like { colName: null }