vue 把后台返回的json拼接成excel并下载

vue

前言

其实这个需求不是很常见,一般是后端接口直接返回流文件,前端调接口下载就行,如果不是有某些特殊需求一定要前端处理,还是建议后端处理下????

先封装一下生成excel的方法

downfile.js

export default {

data() {

return {}

},

components: {},

created() {

},

methods: {

downloadFiles(data,type){

this.JSONToExcelConvertor(data.content, type+"报表", data.title);

},

JSONToExcelConvertor(JSONData, FileName, ShowLabel) {

//先转化json

const arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

let excel = '<table>';

//设置表头

let row = "<tr>";

for (let i = 0, l = ShowLabel.length; i < l; i++) {

row += "<td>" + ShowLabel[i] + '</td>';

}

//换行

excel += row + "</tr>";

//设置数据

for (let i = 0; i < arrData.length; i++) {

let row = "<tr>";

for (let index in arrData[i]) {

const value = arrData[i][index] === "." ? "" : arrData[i][index];

row += '<td>' + value + '</td>';

}

excel += row + "</tr>";

}

excel += "</table>";

let excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";

excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';

excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';

excelFile += '; charset=UTF-8">';

excelFile += "<head>";

excelFile += "<!--[if gte mso 9]>";

excelFile += "<xml>";

excelFile += "<x:ExcelWorkbook>";

excelFile += "<x:ExcelWorksheets>";

excelFile += "<x:ExcelWorksheet>";

excelFile += "<x:Name>";

excelFile += "{worksheet}";

excelFile += "</x:Name>";

excelFile += "<x:WorksheetOptions>";

excelFile += "<x:DisplayGridlines/>";

excelFile += "</x:WorksheetOptions>";

excelFile += "</x:ExcelWorksheet>";

excelFile += "</x:ExcelWorksheets>";

excelFile += "</x:ExcelWorkbook>";

excelFile += "</xml>";

excelFile += "<![endif]-->";

excelFile += "</head>";

excelFile += "<body>";

excelFile += excel;

excelFile += "</body>";

excelFile += "</html>";

const uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);

const 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);

}

}

}

然后在页面中调用

<template>

<div>

<button @click="_sendDownloadFilesServer()">下载报表</button>

</div>

</template>

<script>

import RecordServer from "@/service/record.service"

const recordServer = new RecordServer()

import downloadFileMixin from "@/mixins/downfile" //把上面的文件导入

export default{

data(){

return{

}

},

mixins:[downloadFileMixin],

methods:{

_sendDownloadFilesServer(){

recordServer.sendDownloadFilesServer({

onSuccess:(res)=>{

console.log(res)

this.downloadFiles(res,'火车') // 点击下载文件会下载名为火车报表的excel

},

onFailed:(err)=>{

console.log(err)

}

})

}

}

}

</script>

以上是 vue 把后台返回的json拼接成excel并下载 的全部内容, 来源链接: utcz.com/z/376281.html

回到顶部