Search code examples
angularexceljs

How to import EXCEL file in angular using exceljs


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


Solution

  • 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.js"
                 ]
              }
         }
    
    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);
                  });
    
                });
            });
          }
    

    Also polyfill.ts must reference in this sequence .. import 'exceljs/dist/exceljs.min.js'; import 'zone.js/dist/zone';