• vue中XLSX解析excel文件


    引入XLSX

     1 import XLSX from 'xlsx'
     2 import Vue from 'vue'
     3 const vm = new Vue();
     4 
     5 async function readExcel (file) {
     6   const types = file.name.split('.');
     7   const type = types[types.length - 1];
     8   const fileType = [
     9     'xlsx', 'xls', 'XLSX', 'XLS'
    10   ].some(item => item == type);
    11   if (!fileType) {
    12     vm.$message.error('格式错误!请重新选择')
    13     return
    14   }
    15     
    16   const result = [];
    17   
    18    const loaded =  (row) => {
    19     return new Promise((resolve) =>{
    20       const reader = new FileReader();
    21       reader.onload = function(e) {
    22         const data = e.target.result;
    23         const wb = XLSX.read(data, {
    24           type: 'binary'
    25         });
    26         
    27         wb.SheetNames.forEach((sheetName) => {
    28           result.push(
    29             XLSX.utils.sheet_to_json(wb.Sheets[sheetName], {header:1,defval:''})
    30             /* {
    31             sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName], {header:1,defval:''})
    32             } */
    33           )
    34         });
    35         resolve(true)
    36       };
    37       reader.readAsBinaryString(row)
    38     })
    39   }
    40 
    41   await loaded(file.raw)
    42   return result;
    43 }
    44 
    45 export { readExcel }

    使用

     1 <el-upload ref="upload" accept=".xls,.xlsx" action="" :auto-upload="false" :on-change="handleUpload" :show-file-list="false">
     2                         <el-button type="primary" plain>选择文件</el-button>
     3                         <span>只能上传xls或xlsx文件</span>
     4                         <span>{{form.fileName}}</span>
     5                     </el-upload>
     6 
     7 
     8 handleUpload (file,fileList) {
     9     // readExcel(file)
    10     if(fileList && fileList.length) {
    11         this.ruleForm.fileText = [];
    12         this.ruleForm.fileName = fileList[fileList.length - 1].name;
    13         readExcel(file).then((res) =>{
    14             if (res) {
    15                  const obj = res[0];  
    16                  for(let i = 0; i < obj.length; i ++) {
    17                    const arr = {}
    18                    arr.itemIds = obj[i][0];
    19                    arr.subThemeTitle = obj[i][1];
    20                    this.ruleForm.fileText.push(arr);
    21                }
    22            }
    23        })
    24     }
    25 ,
  • 相关阅读:
    [20180317]12c TABLE ACCESS BY INDEX ROWID BATCHED3.txt
    模态登录
    javascript unshift()和shift()
    登录拦截功能
    springmvc 拦截器的使用小结
    handsontable 和 echarts都定义了require方法,初始化时冲突了,怎么办?
    eclipse缓慢了么?
    springmvc处理日期格式
    hibernate设置了not-null 为什么无效?
    java 和 javascript CryptoJS 进行HmacSHA1加密
  • 原文地址:https://www.cnblogs.com/J-Luck/p/15066768.html
Copyright © 2020-2023  润新知