Vue 导入excel功能

html:

1 <input type="file" @change="importf(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>

js代码:

 1     importf(obj) {
 2       let _this = this;  
 3       this.file = event.currentTarget.files[0];  
 4       var rABS = false; //是否将文件读取为二进制字符串  
 5       var file = this.file; 
 6 
 7       FileReader.prototype.readAsBinaryString = function(f) {  
 8         var binary = "";  
 9         var rABS = false; //是否将文件读取为二进制字符串  
10         var pt = this;  
11         var workbook; //读取完成的数据  
12         // var excelData;  
13         var reader = new FileReader(); 
14         reader.onprogress = function(e) { 
15           let total = file.size;
16           _this.progress = (e.loaded/total)*100;
17           console.log( _this.progress);
18         };   
19         reader.onload = function(e) {
20           try {
21             var bytes = new Uint8Array(reader.result);  
22             var length = bytes.byteLength;  
23             for(var i = 0; i < length; i++) {  
24               binary += String.fromCharCode(bytes[i]);  
25             }  
26             if(rABS) {  
27               workbook = XLSX.read(btoa(fixdata(binary)), { //手动转化  
28                 type: 'base64'  
29               });  
30             }else {  
31               workbook = XLSX.read(binary, {  
32                 type: 'binary'  
33               });  
34             } 
35             // excelData = []; 
36           } catch(e) {
37             console.log('文件类型不正确');
38             return;
39           }
40           var fromTo = '';
41           for (var sheet in workbook.Sheets) {
42             if (workbook.Sheets.hasOwnProperty(sheet)) {
43               fromTo = workbook.Sheets[sheet]['!ref'];
44               _this.excelData = _this.excelData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
45             }
46           }
47           console.log(_this.excelData);
48         };
49 
50         reader.readAsArrayBuffer(f);  
51 
52       } 
53  
54       var reader = new FileReader();
55       if(rABS) {  
56         reader.readAsArrayBuffer(file);  
57       }else {  
58         reader.readAsBinaryString(file);  
59       } 
60 
61       
62     },

注意一下:

需要在data那里定义下excelData变量

data:{
return {
excelData:[],
}
}
这样this.excelData的concat函数才可以使用

参考网址:

https://www.jianshu.com/p/74d405940305

原文地址:https://www.cnblogs.com/zhaomeizi/p/8743106.html