typescript 以角度2读取excel文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48112236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:09:14  来源:igfitidea点击:

Read excel file in angular 2

javascriptangulartypescriptng2-file-upload

提问by Asad Shah

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.

我正在使用ng2-File-upload,我想读取 excel 文件及其所有行并获取总数。有什么方法可以通过使用此模块以及如何通过纯 JavaScript 或打字稿完成它来实现它。

回答by Asad Shah

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

我使用了接受的答案中提到的包。 ng2-file-upload有一个uploader回调函数this.uploader.onAfterAddingFile。我刚刚调用了我的更改函数并读取了如下文件:

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

希望它可以帮助任何人:)