Angular 4: How to read data from Excel?

前端 未结 5 1998
孤城傲影
孤城傲影 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:25

    I've tried the file upload and below is my steps and result with both data and header,

    This will also support multiple sheet within the excel sheet,

    1.npm install --save xlsx
        
    2.import * as XLSX from 'xlsx';
    
    3.HTML Code:
    
    
    
    4.Angular Typescript:
    
      exceltoJson = {};
    
      onFileChange(event: any) {
        this.exceltoJson = {};
        let headerJson = {};
        /* 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]);
        console.log("filename", target.files[0].name);
        this.exceltoJson['filename'] = target.files[0].name;
        reader.onload = (e: any) => {
          /* create workbook */
          const binarystr: string = e.target.result;
          const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'binary' });
          for (var i = 0; i < wb.SheetNames.length; ++i) {
            const wsname: string = wb.SheetNames[i];
            const ws: XLSX.WorkSheet = wb.Sheets[wsname];
            const data = XLSX.utils.sheet_to_json(ws); // to get 2d array pass 2nd parameter as object {header: 1}
            this.exceltoJson[`sheet${i + 1}`] = data;
            const headers = this.get_header_row(ws);
            headerJson[`header${i + 1}`] = headers;
            //  console.log("json",headers)
          }
          this.exceltoJson['headers'] = headerJson;
          console.log(this.exceltoJson);
        };
      }
    
      get_header_row(sheet) {
        var headers = [];
        var range = XLSX.utils.decode_range(sheet['!ref']);
        var C, R = range.s.r; /* start in the first row */
        /* walk every column in the range */
        for (C = range.s.c; C <= range.e.c; ++C) {
          var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
          // console.log("cell",cell)
          var hdr = "UNKNOWN " + C; // <-- replace with your desired default 
          if (cell && cell.t) {
            hdr = XLSX.utils.format_cell(cell);
            headers.push(hdr);
          }
        }
        return headers;
      }
    
    5.Result
    {filename: "uploadedexcel.xlsx", sheet1: Array(212), sheet2: Array(8), headers: {…}}
    

    Results holds the uploaded excel name, data in the sheet1 and sheet2 and also header in the sheet1 and sheet2.

    The uploaded excel sheets has sheet1 and sheet2.

提交回复
热议问题