How to import EXCEL file in angular using exceljs

梦想的初衷 提交于 2019-12-13 03:49:26

问题


I want to read excel file using angular code. my file is stored somewhere in my local system e.g, C:/data/test.xlsx

I have already tried loading with readFile() & load() methods of exceljs.

they fail to read anything, instead they give error


回答1:


I found the way to read excel file from Angular code. Convert the file into ArrayBuffer and read it using exceljs

  1. Importing Exceljs in angular service/component
    import * as Excel from 'exceljs/dist/exceljs.min.js';

  1. Modify tsconfig.app.json
    compilerOptions: {
       paths": {
             "exceljs": [
               "node_modules/exceljs/dist/exceljs.min"
             ]
          }
     }
  1. Open file from html code.
    <input id="uploadBtn" type="file" (change)="readExcel($event)" 
           class="upload input-common" required />

  1. Using exceljs for reading file.
    readExcel(event) {
        const workbook = new Excel.Workbook();
        const target: DataTransfer = <DataTransfer>(event.target);
        if (target.files.length !== 1) {
          throw new Error('Cannot use multiple files');
        }

        /**
         * Final Solution For Importing the Excel FILE
         */

        const arryBuffer = new Response(target.files[0]).arrayBuffer();
        arryBuffer.then(function (data) {
          workbook.xlsx.load(data)
            .then(function () {

              // play with workbook and worksheet now
              console.log(workbook);
              const worksheet = workbook.getWorksheet(1);
              console.log('rowCount: ', worksheet.rowCount);
              worksheet.eachRow(function (row, rowNumber) {
                console.log('Row: ' + rowNumber + ' Value: ' + row.values);
              });

            });
        });
      }


来源:https://stackoverflow.com/questions/56595103/how-to-import-excel-file-in-angular-using-exceljs

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