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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM