Read excel file in angular 2

Asad Shah picture Asad Shah · Jan 5, 2018 · Viewed 15.1k times · Source

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.

Answer

Asad Shah picture Asad Shah · Jan 5, 2018

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 :)