vue读取excel数据生成数组

  1. 首先安装 npm install xlsx
  2. html中 <input type="file" ref="upload" accept=".xls,.xlsx" class="outputlist_upload">
  3. 引入 import XLSX from 'xlsx'

代码如下:

 1 <template>
 2   <div class="hello">
 3     <input type="file" ref="upload" accept=".xls,.xlsx" class="outputlist_upload">
 4   </div>
 5 </template>
 6 
 7 <script>
 8 
 9 import Vue from 'vue'
10 import XLSX from 'xlsx'
11 export default {
12   name: 'tab1',
13   data () {
14     return {
15       outputs: []
16     }
17   },
18   mounted() {
19     this.$refs.upload.addEventListener('change', e => {//绑定监听表格导入事件
20     this.readExcel(e);
21     })
22   },
23   methods: {
24      readExcel(e) {//表格导入
25         var that = this;
26         const files = e.target.files;
27         console.log(files);
28         if(files.length<=0){//如果没有文件名
29           return false;
30         } else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
31           this.$Message.error('上传格式不正确,请上传xls或者xlsx格式');
32           return false;
33         }
34  
35         const fileReader = new FileReader();
36         fileReader.onload = (ev) => {
37         try {
38             const data = ev.target.result;
39             const workbook = XLSX.read(data, {
40             type: 'binary'
41             });
42             const wsname = workbook.SheetNames[0];//取第一张表
43             const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
44             console.log(ws);
45             that.outputs = [];//清空接收数据
46             for(var i= 0;i<ws.length;i++){
47             var sheetData = {
48                 name: ws[i].name,
49                 sex: ws[i].sex,
50                 name: ws[i].age
51             }
52             that.outputs.push(sheetData);
53             }
54             this.$refs.upload.value = '';
55  
56         } catch (e) {
57           return false;
58         }
59       };
60       fileReader.readAsBinaryString(files[0]);
61     },
62     btn () {
63       console.log(Vue)
64     }
65   }
66 }
67 </script>
68 
69 <!-- Add "scoped" attribute to limit CSS to this component only -->
70 <style scoped>
71 </style>