Angular 4: How to read data from Excel?

前端 未结 5 2008
孤城傲影
孤城傲影 2020-12-01 11:09

I am not able to get data from an Excel sheet in Angular 4. Below is my code sample.

HTML code:



        
5条回答
  •  我在风中等你
    2020-12-01 11:36

    You can use SheetJs/xlsx package from npm to get the data from excel as a json object in Angular / Ionic.

    Just follow these steps:

    1) npm install --save xlsx

    2) Now in your component file import xlsx

    import * as XLSX from 'xlsx';
    

    3) Now attach this function in the change event of input tag of type file

    onFileChange(event: any) {
        /* wire up file reader */
        const target: DataTransfer = (event.target);
        if (target.files.length !== 1) {
          throw new Error('Cannot use multiple files');
        }
        const reader: FileReader = new FileReader();
        reader.readAsBinaryString(target.files[0]);
        reader.onload = (e: any) => {
          /* create workbook */
          const binarystr: string = e.target.result;
          const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'binary' });
    
          /* selected the first sheet */
          const wsname: string = wb.SheetNames[0];
          const ws: XLSX.WorkSheet = wb.Sheets[wsname];
    
          /* save data */
          const data = XLSX.utils.sheet_to_json(ws); // to get 2d array pass 2nd parameter as object {header: 1}
          console.log(data); // Data will be logged in array format containing objects
        };
     }
    

    You can also refer to these utils method present in xlsx to perform different operation according to your need.

    https://github.com/SheetJS/sheetjs#utility-functions

    And also during read operation you can pass these parsing options inside object

    https://github.com/SheetJS/sheetjs#parsing-options

    For any other information refer to the doc

    https://github.com/SheetJS/sheetjs

    Hope this will help you or somebody else.

提交回复
热议问题