0

I am Using XLSX npm package to read the data from Excel and convert into JSON format

I'm using Angular 7.

     const reader = new FileReader();
     const file = ev.target.files[0];
     reader.onload = (event) => {
       const data = reader.result;
       console.log(data);
       workBook = XLSX.read(data, { type: 'binary' });
       jsonData = workBook.SheetNames.reduce((initial, name) => {
         const sheet = workBook.Sheets[name];
         initial[name] = XLSX.utils.sheet_to_json(sheet);
         return initial;
       }, {});
       const dataString = JSON.stringify(jsonData);
     };

Tried using reader.onload and reader.onloadend, it's not even throwing an error but the events are not firing. Can anyone help how to make it work? Thanks in Advance.

2 Answers2

1

Here is working Example

 onFileChange(ev) {
    let workBook = null;
    let jsonData = null;
    const reader = new FileReader();
    const file = ev.target.files[0];
    reader.onload = (event) => {
      const data = reader.result;
      workBook = XLSX.read(data, { type: 'binary' });
      jsonData = workBook.SheetNames.reduce((initial, name) => {
        const sheet = workBook.Sheets[name];
        initial[name] = XLSX.utils.sheet_to_json(sheet);
        return initial;
      }, {});
      const dataString = JSON.stringify(jsonData);
      document.getElementById('output').innerHTML = dataString.slice(0, 300).concat("...");
      this.setDownload(dataString);
    }
    reader.readAsBinaryString(file);
  }
Chanaka Weerasinghe
  • 5,404
  • 2
  • 26
  • 39
0

The events are not firing because you are not calling any read method on your file object . You need to call one of the read methods on your file object for one of the events to get fired.

The file reader read methods are - https://developer.mozilla.org/en-US/docs/Web/API/FileReader#Methods

And the event handlers are - https://developer.mozilla.org/en-US/docs/Web/API/FileReader#Event_handlers

You can read more about the usage of reader methods by clicking on one of them eg- https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

Basically , In your code you just need to add some read method at the end like -

     const reader = new FileReader();
     const file = ev.target.files[0];
     reader.onload = (event) => {
       const data = reader.result;
       console.log(data);
       workBook = XLSX.read(data, { type: 'binary' });
       jsonData = workBook.SheetNames.reduce((initial, name) => {
         const sheet = workBook.Sheets[name];
         initial[name] = XLSX.utils.sheet_to_json(sheet);
         return initial;
       }, {});
       const dataString = JSON.stringify(jsonData);
     };

    // ADD THIS IN YOUR CODE
    reader.readAsDataURL(file);
Pawan Sharma
  • 1,842
  • 1
  • 14
  • 18