sheetjs匯出xlsx:更改欄位名稱

try更替物件屬性名稱、json to xlsx

by cactus77kiki

HTML

<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>

<div id="vapp">
  <h3>更替物件屬性名稱+json資料匯出excel(單一sheet)</h3>  
  <!--{{msg}}-->
  <!--{{dataVal}}-->
  <button type="button" v-on:click="downloadxfile">
    Download Excel
  </button> 
  
</div>

JavaScript

var app = new Vue({
	el:'#vapp',
  data: {
  	//msg:'test'
    dataVal: [],
    headerVal:[{text: '文章代碼', value: 'postId'},{text: '文章名稱', value: 'name'},
    					 {text: '信箱', value: 'email'},{text: '文章內容', value: 'body'},
               {text: '時數', value: 'etime'},
               {text: '功能', value: 'actions', sortable: false}]               
  },
  created: function(){
  	this.getdata();
  },
  methods:{
  	getdata: function(){
    	this.dataVal = [{'postId': 1, "name": "id labore ex ",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam 1","etime":'1.50'},
    {'postId': 2, "name": "att labore ex et ",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam 2","etime":'4.50'},
    {'postId': 3, "name": "c labore ex et 33",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam 3","etime":'8.00'},
    {'postId': 4, "name": "c labore ex et 33",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam 4","etime":'2.00'}
      ];      
    },
  	downloadxfile: function(){    	
      let arry = [];
      let jsonheader = this.headerVal.map(x=>x.value);	//取得所有欄位名稱 
      
      for(let j=0;j< this.dataVal.length;j++){
          let dataobj = this.dataVal[j];
          let obj = {};
          //console.log(dataobj);
          for(let k=0;k< this.headerVal.length;k++){          		 /*let headvalue= jsonheader[k]; 
            let headobj = this.headerVal.filter(function (item) {
							return item.value == headvalue;
						});
            
            let headtext = headobj[0].text;
            obj[headtext] = dataobj[headvalue];*/
            
            obj[this.headerVal[k].text] = this.dataVal[j][this.headerVal[k].value]  //dataobj[headvalue];            
          }
          
          arry.push(obj);
       }
       console.log(arry);  
       downloadxlsx("abc.xlsx","sheet1",arry);
        
       
    },
    
  }
});

/*json...