5

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?

2 Answers 2

7

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);
  }
Sign up to request clarification or add additional context in comments.

Comments

0

In my case i want data like

[['1','2'],['3','4']]

also data like

{'1':'3', '2':'4'}

So that i did following code

uploadFile(uploadedFile){
    let workBook = null;
    const reader = new FileReader();
    const file = uploadedFile[0];
    reader.onload = (event) => {
      const data = reader.result;
      workBook = XLSX.read(data, { type: 'binary' });
      const sheet_name_list = workBook.SheetNames;

      this.xlData = XLSX.utils.sheet_to_json(workBook.Sheets[sheet_name_list[0]]);
      log("xlData >>> ",JSON.stringify(this.xlData));

      this.arraySaparater = (XLSX.utils.sheet_to_json(workBook.Sheets[sheet_name_list[0]], { header: 1 }));
      this.arraySaparater = this.arraySaparater.filter((row)=>{
        if(Array.isArray(row) && row.length){
          return row;
        }
        else{
          return false;
        }
      });
      log('ArraySaparater >>>',JSON.stringify(this.arraySaparater));

    }
    reader.readAsBinaryString(file);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.