如何使用 exceljs 在 angular 中导入 EXCEL 文件

How to import EXCEL file in angular using exceljs

我想使用 angular 代码读取 excel 文件。 我的文件存储在本地系统的某个地方,例如 C:/data/test.xlsx

我已经尝试加载 exceljs.

的 readFile() 和 load() 方法

他们无法读取任何内容,而是给出错误

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

  1. 在angular中导入Exceljs 服务/组件
    import * as Excel from 'exceljs/dist/exceljs.min.js';

  1. 修改tsconfig.app.json
    compilerOptions: {
       paths": {
             "exceljs": [
               "node_modules/exceljs/dist/exceljs.min.js"
             ]
          }
     }
  1. 从 html 代码打开文件。
    <input id="uploadBtn" type="file" (change)="readExcel($event)" 
           class="upload input-common" required />

  1. 使用exceljs读取文件。
    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);
              });

            });
        });
      }

另外 polyfill.ts 必须按此顺序引用 .. import 'exceljs/dist/exceljs.min.js'; import 'zone.js/dist/zone';