Excel到JSON转换器Angular 2

问题描述 投票:1回答:2

我想解析XLSX文件并将其转换为Angular 2中的JSON。我使用下面的代码来读取和解析文件readFile(){

var testUrl= "../assets/US175939.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", testUrl, true);
oReq.responseType = "arraybuffer";

oReq.onload = function(e) {
  var arraybuffer = oReq.response;

  /* convert data to binary string */
  var data = new Uint8Array(arraybuffer);
  var arr = new Array();
  for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
  var bstr = arr.join("");
  console.log("Data"+bstr);

  /* Call XLS */
  var workbook = XLSX.read(bstr, {type:"binary"});


  /* DO SOMETHING WITH workbook HERE */
}

oReq.send();
}

这里的错误是 - “找不到名称XLSX”。

请建议我使用角度2将Excel转换为JSON的一些解决方案。

angular
2个回答
1
投票

我在Angular中编写了一个服务,将excel转换为JSON,反之亦然。步骤: - 1)npm install xlsx --save 2)npm install file-saver --save

import { Injectable } from '@angular/core';
import {saveAs} from 'file-saver'; 
import {  WorkBook, read, utils, write, readFile } from 'xlsx';
@Injectable()
export class FileExcelService {

  wbout = [];
  table = [];
   ws: any;
  constructor() { 
    this.setExcelProperties('');
  }

  s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) {
      view[i] = s.charCodeAt(i) & 0xFF;
    };
    return buf;
  }


  SaveToExcel(tableData, fileName: string= 'QuestionSheet') {
    this.setTableData(tableData,fileName);
    saveAs(new Blob([this.s2ab(this.wbout)], { type: 'application/octet-stream' }), fileName+'.xlsx');
   }

   getTableData()
   {
     return this.table;
   }

   setTableData(tableData, fileName: string)
   {
     this.table = tableData;
     this.setExcelProperties(fileName);
   }


   // excel Detail
   setExcelProperties(fileName: string)
   {
    const ws_name = fileName.substr(0, 25); //'QuestionSheet'
  //  const ws_name = ''; // worksheet name cannot exceed 31 chracters length
    const wb: WorkBook = { SheetNames: [], Sheets: {} };
    this.ws = utils.json_to_sheet(this.getTableData());
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = this.ws;
     this.wbout = write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });
   }

   convertExcelToJson(file)
   {
    let reader = new FileReader();
    let workbookkk;
    let XL_row_object;
    let json_object;
    reader.readAsBinaryString(file);
    return new Promise((resolve, reject) => {
      reader.onload = function(){
        //  alert(reader.result);
        let data = reader.result;
         workbookkk=read(data,{type: 'binary'});
         console.log(workbookkk);
         workbookkk.SheetNames.forEach(function(sheetName) {
          // Here is your object
           XL_row_object = utils.sheet_to_json(workbookkk.Sheets[sheetName]);
           json_object = JSON.stringify(XL_row_object);
        //  console.log(json_object);
        //  console.log(XL_row_object);
            resolve(XL_row_object);
        });
        };
    });
    }
}

0
投票

我找到了解决方案。希望它能帮助所有人:

//读取文件readFile(){

var testUrl= "../assets/US175939.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", testUrl, true);
oReq.responseType = "arraybuffer";

oReq.onload = function(e) {
  var arraybuffer = oReq.response;

  /* convert data to binary string */
  var data = new Uint8Array(arraybuffer);
  var arr = new Array();
  for(var i = 0; i != data.length; ++i){ arr[i] = String.fromCharCode(data[i]);
    //  console.log("Data"+data[i]);
  }
  var bstr = arr.join("");
  var workbook = XLSX.read(bstr, {type:"binary"});
//console.log("Data"+bstr);
 var first_sheet_name = workbook.SheetNames[0];
  /* Get worksheet */
  var worksheet = workbook.Sheets[first_sheet_name]; 
  var json = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1, raw:true});
  var jsonOut = JSON.stringify(json);
   console.log("test"+jsonOut);
}

oReq.send();

}
热门问题
推荐问题
最新问题