Reading local Excel file with js-xlsx using Angular 9?

瘦欲@ 提交于 2020-06-15 06:27:18

问题


I have my Angular-CLI frontend development server running locally on localhost:4200

For specific reasons I need to get a local Excel file stored on my PC, read its content and make some calls to an API. And it must be from the client side.

I'm trying to use js-xlsx, got it installed with npm install xlsx but I can't find how to get the file and read its content.

How can I import a local excel file with js-xlsx in Angular 9?

Note: If it is possible/easier using pure JavaScript it is also valid for me.


回答1:


Here is working Example

onFileChange(ev) {
    let workBook = null;
    let jsonData = null;
    const reader = new FileReader();
    const file = ev.target.files[0];
    reader.onload = (event) => {
      const data = reader.result;
      workBook = XLSX.read(data, { type: 'binary' });
      jsonData = workBook.SheetNames.reduce((initial, name) => {
        const sheet = workBook.Sheets[name];
        initial[name] = XLSX.utils.sheet_to_json(sheet);
        return initial;
      }, {});
      const dataString = JSON.stringify(jsonData);
      document.getElementById('output').innerHTML = dataString.slice(0, 300).concat("...");
      this.setDownload(dataString);
    }
    reader.readAsBinaryString(file);
  }



回答2:


In my case i want data like

[['1','2'],['3','4']]

also data like

{'1':'3', '2':'4'}

So that i did following code

uploadFile(uploadedFile){
    let workBook = null;
    const reader = new FileReader();
    const file = uploadedFile[0];
    reader.onload = (event) => {
      const data = reader.result;
      workBook = XLSX.read(data, { type: 'binary' });
      const sheet_name_list = workBook.SheetNames;

      this.xlData = XLSX.utils.sheet_to_json(workBook.Sheets[sheet_name_list[0]]);
      log("xlData >>> ",JSON.stringify(this.xlData));

      this.arraySaparater = (XLSX.utils.sheet_to_json(workBook.Sheets[sheet_name_list[0]], { header: 1 }));
      this.arraySaparater = this.arraySaparater.filter((row)=>{
        if(Array.isArray(row) && row.length){
          return row;
        }
        else{
          return false;
        }
      });
      log('ArraySaparater >>>',JSON.stringify(this.arraySaparater));

    }
    reader.readAsBinaryString(file);
}


来源:https://stackoverflow.com/questions/57818105/reading-local-excel-file-with-js-xlsx-using-angular-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!