javascriptexcelangularfilejs-xlsx

Reading local Excel file with js-xlsx using Angular 13?


I have my Angular-CLI frontend development server running locally on localhost:4200

I need to get a local Excel file stored on my PC, read its content and make some calls to an API from the client side.

I'm trying to use js-xlsx, got it installed with npm install xlsx but I can't find how to get the file and read its content.

How can I import a local excel file with js-xlsx in Angular 13?


Solution

  • 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);
      }