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

Iñigo picture Iñigo · Sep 6, 2019 · Viewed 13.8k times · Source

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

For specific reasons I need to get a local Excel file stored on my PC, read its content and make some calls to an API. And it must be 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 12?

Note: If it is possible/easier using pure JavaScript it is also valid for me.

Answer

Chanaka Weerasinghe picture Chanaka Weerasinghe · Sep 6, 2019

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