angular - 如何使用exceljs以 Angular 导入EXCEL文件

标签 angular 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


  • 以 Angular 导入 Exceljs 服务/组件
  •     import * as Excel from 'exceljs/dist/exceljs.min.js';
    

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

  • 使用 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';

    关于angular - 如何使用exceljs以 Angular 导入EXCEL文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56595103/

    相关文章:

    javascript - 如何停止 array.filter() 函数

    javascript - angular2 xhrfields withcredentials true

    angular - 在 Angular 2 中使用父组件中的子组件

    javascript - ExcelJS Node : horizontalCentered & verticalCentered in page not working

    javascript - 嵌套异步等待未按预期工作

    node.js - Node exceljs读取文件

    未触发 Angular 4 动画, "ng-animate-queued"类已添加到元素

    Angular 2 - 布局组件

    node.js - Exceljs数据验证列表导致Excel女士出错

    node.js - 修改现有Excel文件而不改变原始格式和链接