Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read excel file in angular 2

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.

like image 450
Asad Shah Avatar asked Jan 05 '18 11:01

Asad Shah


1 Answers

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

like image 94
Asad Shah Avatar answered Oct 22 '22 00:10

Asad Shah