前端通过json数据导出excel表格文件(支持多级表头、复杂表头)(json转excel)

downloadBmExcel(){
	    		let vm = this;
	    		let titles = ["顺序号","责任者","文号","标题","日期","页号","备注"];
	    		let keys = ['index',null,null,'name',null,'range',null];
				let groups = [];
				vm.groups.map((v)=>{
					if(!v.type){
						groups.push(v);
					}
				})
	    		JSONToExcelConvertor(groups,vm.volumeName+"_智能编目目录",titles,keys);
	    	},
	    	
console.log(groups)//数据格式
					//0:
					//editing: false
					//id: "c9e9bc6b8a200001c9eb127049c02a00"
					//index: 0
					//ismulu: true
					//list: Array(3)
					//name: "讯问笔录((被告)第1次"
					//range: "1-3"
					//respon: ""
					//select: false

封装
export function JSONToExcelConvertor (JSONData, FileName, title, keys, notital, titleH) {
  if (!JSONData) { return }
    // 转化json为object
  var arrData = typeof JSONData !== 'object' ? JSON.parse(JSONData) : JSONData

  var excel = ''// 设置表头var row = notital ?'':"'if(title){// 使用标题项for(var i in title){
      row +="'}}else{// 不使用标题项for(var i in arrData[0]){
      row +="'}}

  excel += row +''// 设置数据for(var i =0; i < arrData.length; i++){var row =''for(var k in title){if(!keys[k]){
        row +=""}else{
        row +="'}}// for (var index in arrData[i]) {//     //判断是否有过滤行//     if(filter)//     {//         if(filter.indexOf(index)==-1)//         {//              var value = arrData[i][index] == null ? "" : arrData[i][index];//              row += '';//         }//     }//     else//     {//          var value = arrData[i][index] == null ? "" : arrData[i][index];//          row += "";//     }// }
    excel += row +''}

  excel +='
" + (titleH || '卷内文件目录') + '
" + title[i] + ' " + i + '
" + arrData[i][keys[k]] + ' ' + value + ' " + value + "
'
var excelFile = "" excelFile += '' excelFile += '' excelFile += '' excelFile += '' excelFile += '' excelFile += excel excelFile += '' excelFile += '' var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile) var link = document.createElement('a') link.href = uri link.style = 'visibility:hidden' link.download = FileName + '.xls' document.body.appendChild(link) link.click() document.body.removeChild(link) }

你可能感兴趣的:(前端,json,javascript)