7

I am using ng2-File-upload,i want to read the excel file and all its rows and get the total count. Is there any way i can achieve it by using this module and how to get it done by plain JavaScript or typescript.

Asad Shah
  • 771
  • 2
  • 8
  • 22

1 Answers1

10

I used the package mentioned in the accepted answer. ng2-file-upload has a uploader that has a call back function this.uploader.onAfterAddingFile. I just called my change function and read the file as below:

 onFileChange(file: any) {
    /* wire up file reader */
    //const target: DataTransfer = <DataTransfer>(evt.target);
    //if (target.files.length !== 1) throw new Error('Cannot use multiple files');
    const reader: FileReader = new FileReader();
    reader.onload = (e: any) => {
        /* read workbook */
        const bstr: string = e.target.result;
        const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

        /* grab first sheet */
        const wsname: string = wb.SheetNames[0];
        const ws: XLSX.WorkSheet = wb.Sheets[wsname];

        /* save data */
        var data = <any>(XLSX.utils.sheet_to_json(ws, { header: 1 }));
        this.totalInventories = data.length > 0 ? data.length - 1 : 0;
    };
    if (file._file)
        reader.readAsBinaryString(file._file);
 }

Hope it helps anyone :)

Asad Shah
  • 771
  • 2
  • 8
  • 22
  • The github repo where you got the code above: https://github.com/SheetJS/js-xlsx/tree/4109caeadd95baca58c7c2481aebf2014ae462bd/demos/angular2 – Rilcon42 Jun 20 '19 at 16:12