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


免責聲明!

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



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