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

前言

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

 

先封装一下生成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 = '';

      //设置表头
      let row = "";
      for (let i = 0, l = ShowLabel.length; i < l; i++) {
        row += "';
      }
      //换行
      excel += row + "";
      //设置数据for (let i = 0; i < arrData.length; i++) {
        let row = "";

        for (let index in arrData[i]) {
          const value = arrData[i][index] === "." ? "" : arrData[i][index];
          row += '';
        }

        excel += row + "";
      }

      excel += "
" + ShowLabel[i] + '
' + value + '
"; let excelFile = ""; excelFile += ''; excelFile += '; excelFile += '; charset=UTF-8">'; excelFile += ""; excelFile += ""; excelFile += ""; excelFile += ""; excelFile += excel; excelFile += ""; excelFile += ""; 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); } } }

然后在页面中调用



 

你可能感兴趣的:(vue 把后台返回的json拼接成excel并下载)