JS处理excel导入转化成array

in Linux with 2 comments

这里用到sheetJs库。
cdn:https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.8/xlsx.min.js
项目地址:https://github.com/SheetJS/sheetjs
首先创建filePicked函数,把读取的EXCEL数据转换成JS ARRAY 通过回调进行操作,

var filePicked= function(file, callback) {
    // Get The File From The Input 
    // var oFile = dom.target.files[0];
    var oFile = file;
    var sFilename = oFile.name;
    // Create A File Reader HTML5
    var reader = new FileReader(); 
    // Ready The Event For When A File Gets Selected
    reader.onload = function(e) {
        var data = e.target.result; 
        var cfb = XLSX.read(data, {type: 'binary'});
        // console.log(cfb)
        var allOjs = {};
        cfb.SheetNames.forEach(function(sheetName) {
            // Obtain The Current Row As CSV
            // var sCSV = XLS.utils.make_csv(cfb.Sheets[sheetName]);   
            var oJS = XLS.utils.sheet_to_json(cfb.Sheets[sheetName]);   
            allOjs[cfb.SheetNames.indexOf(sheetName)] = oJS
            // $("#my_file_output").html(sCSV);
            // return oJS
        });
        if(callback){
            callback(allOjs)
        }
    }; 
    // Tell JS To Start Reading The File.. You could delay this if desired
    reader.readAsBinaryString(oFile);
    // return reader
}

html:

<form enctype="multipart/form-data" id="importForm">
  <div class="row">
               
           
     <div class="col-md-3">
       <input type="file" class="form-control" name="im_file" id="im_file" accept=".xlsx">
     </div>
     <div class="col-md-3">
         <button class="button is-info" type="submit">导入</button>
      </div>
   </div>
</form>

js:

$("#importForm").submit(function (e) {
    e.preventDefault();
    var formData = new FormData();
    var im_file = $("#im_file")[0].files[0];
    filePicked(im_file, function (data) {
          var arr = data[0];  //第一个工作表
          // arr是EXCEL转化的JS ARRAY, 这里你可以写你的业务逻辑了。
           
    })
})
Comments are closed.