• 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 ,
  • 相关阅读:
    宝塔面板定时/同步备份网站及数据库至FTP存储空间完整教程
    Heroku是部署又是网站空间? github是仓库
    python批量添加hexo文章封面
    hexo史上最全搭建教程
    小皮面板一款好像还不错的 Linux 管理面板
    [Python] Hexo博文图片上传图床并自动替换链接的Python脚本
    5分钟搞定个人博客-hexo
    python的嵌入式开发
    Windows Embedded CE 6.0开发环境的搭建(2)
    EPLAN中的edz文件的用法
  • 原文地址:https://www.cnblogs.com/J-Luck/p/15066768.html
Copyright © 2020-2023  润新知