Excel to JSON converter in Angular 2

2019-09-20 09:19发布

问题:

I want to parse and excel file to JSON. How can we achieve this in Angular 2. I have tried excel-as-json through npm but it is not working

回答1:

You can use XLSX modlue to extract data from excel.

makeJSON() {
  for(var i=0;i<execlData.length;i++) {
    if(execlData[i] && execlData[i].length > 0) {
      this.items.push({
        'param1': execlData[i][0],
        'param2': execlData[i][1],
        'param3': execlData[i][2],
        'param4': execlData[i][3],
      });
    }
  }
}

var reader = 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 */
  let execlData = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1}));

  this.makeJSON(execlData);
  
};



回答2:

Does the transformation have to happen from the file itself to JSON? This would be much more easily handled (comparatively) as a formula in Excel to transform and output the values in Excel to JSON nodes.



标签: angular