zoukankan      html  css  js  c++  java
  • AngularJS之前端解析excel文件

    之前发现一款比较强大的js解析excel插件SheetJS js-xlsx,一直未投入到生产中使用。最近有批量导入的需求,大致看了下文档,使用比较方便快捷,容易上手,现在以AngularJS为例,介绍下其基本使用:

    1、下载核心js文件xlsx.full.min.js,通过script标签引入到项目中

      github地址:https://github.com/sheetjs/js-xlsx

    2、编写自定义指令

     1  xxx.directive('importSheet', function () {
     2     return {
     3       scope: {opts: '='},
     4       link: function ($scope, $element, $attr) {
     5         /**
     6          * exp:<input type="file" name="uploadExcel" data-sheetname="批量导入" import-sheet multiple="false" />
     7          */
     8         //表格所在sheet页名称
     9         var sheetName = $attr.sheetname;
    10         $scope.dataList = [];
    11         $element.on('change', function (changeEvent) {
    12           var reader = new FileReader();
    13           reader.onload = function (e) {
    14             var bstr = e.target.result;
    15             var workbook = XLSX.read(bstr, {type: 'binary'});
    16             console.log('workbook', workbook)
    17             //将原始excel数据解析成json
    18             var dataList = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
    19             console.log('dataList', dataList);
    20           };
    21           reader.readAsBinaryString(changeEvent.target.files[0]);
    22         })
    23       }
    24     }
    25   })

    3、在页面中使用此自定义指令,导入后的结果如下:

      原始数据:

      json格式的数据:

      

      同时,xlsx自带很多工具方法,可以根据实际业务需求酌情考虑:

      

  • 相关阅读:
    [LeetCode] Convert Sorted Array to Binary Search Tree
    [LeetCode] Diameter of Binary Tree
    [LeetCode] Student Attendance Record I
    [LeetCode] Reverse String II
    [LeetCode] Missing Number
    [LeetCode] Intersection of Two Arrays II
    [LeetCode] Base 7
    Ubuntu中firefox设置成中文
    Linux中的查找命令find
    Ubuntu14.04安装配置Chrome浏览器
  • 原文地址:https://www.cnblogs.com/gerry2019/p/10291664.html
Copyright © 2011-2022 走看看