vue.js-excel上傳(組件)

by cactus77kiki

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.8/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>


<div id="vapp">
  <h3>上傳excel檔案轉json資料</h3>
  <ele-upload-excel :beforeupload="checkbeforeupload" :errormsg="errormessage" :getdata="getfiledata" :titledata="titles">    
  </ele-upload-excel>
</div>

CSS

/*
vue.js自製上傳按鈕,另可study下文:
https://tools.wingzero.tw/article/sn/115
*/

JavaScript

/*
ref1: https://stackoverflow.com/questions/54456751/vuejs-input-file-form
ref2: https://www.wikimoe.com/?post=157
ref3: https://blog.zhulu.tech/js/2017/05/13/
*/

Vue.component('ele-upload-excel',{
	props:{
  	beforeupload:{type: Function},	//上傳前檢核
    getdata:{type:Function},	//取得資料
    errormsg:{type: String},	//上傳前檢核錯誤訊息
    titledata:{type:Array}	//回傳資料指定欄位名稱
  },
  data: function (){
  	return {
    	filename: "",	//檔名
      filedata: [],	//檔案內容      
      title:this.titledata,
      formatmsg: "格式有誤,請上傳xlsx格式檔案",	//格式錯誤訊息
      checkerrmsg: this.errormsg == "" ? "無法上傳檔案!" : this.errormsg	//檢核未過錯誤訊息預設值
    }
  },  
  template:
  `
  <div class="form-inline" style="margin:3px;">  
  	<button class="btn btn-primary btn-sm" v-on:click="trigerupload"><i class="fa fa-upload" aria-hidden="true"></i> 上傳檔案</button>
  	<input type="file" style="display: none;" ref="fileInput" v-on:click="resetUpload" v-on:change="goUpload($event)" accept=".xls,.xlsx">
  	<!--<input v-model="filename" type="text" style="width:190px;" class="form-control input-sm" readonly placeholder="請按『上傳』按鈕選擇檔案">-->
  </div>
  `,
  methods:{  	
  	trigerupload: function(){    	
    	var result = this.beforeupload();
      if(this.beforeupload())
    		this.$refs.fileInput.click();
      else
      	alert(this.checkerrmsg);
    },
  	resetUpload: function(){
    	this.$refs.fileInput.value = "";
    },
    goUpload: function(event){
    	var filer = event.target.files;            
      if(filer.length<=0){//如果没有文件名
        return false;
      }else if(!/\.(xls|xlsx)$/.test(filer[0].name.toLowerCase())){
      	alert(this.formatmsg);
        return false;
      }      
      //轉json
      var self = this;
      var fileReader = new FileReader();
      fileReader.onload = function(e) {
        try {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary' });
            var first_sheet_name = workbook.SheetNames[0];
    				var worksheet =...