ElementUI 下载文件前后端代码

前端代码
store 中的js文件

import {excelExportTemplate
  }   from '@/api/xxxxx'
 async excelExportTemplate ({commit}, fieldConfig) {
    var res =await new Promise((resolve, reject) => {
      excelExportTemplate(fieldConfig).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
    return res
  },

api总的方法

import request from '@/utils/request'
const prefix = 'xxxxxx/'
export function excelExportTemplate (params) {
    return request.post(prefix + 'excelExportTemplate',params, {
      responseType: 'blob',
    });//请求时,数据格式为blob
  }

request由于是封装的方法,增加blob格式方法
const res = response.data
    if (response.data instanceof Blob&&response.status=="200"){
      return res
    }

vue中的方法

excelExportTemplateBtn: function () {
        var querystring = require('querystring')
              var param = {}
              this.excelExportTemplate(querystring.stringify(param))
                .then(resp => {
                  this.downloadExcel(resp,'字段映射配置模板.xlsx')
                  this.$message({
                    type: 'success',
                    message:
                      '下载成功!'
                  });
                })
      },
downloadExcel (blobPart, filename) {
        const blob = new Blob([blobPart], { type: 'application/vnd.ms-excel' })
        // 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
        const elink = document.createElement('a')
        elink.download = decodeURIComponent(filename)
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      },

后端代码

@RequestMapping("excelExportTemplate")
    public void excelExportTemplate( HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("字段映射配置模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<EntityVo> list = new ArrayList<EntityVo>();
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), EntityVo.class)
                    .head(EntityVo.class)
                    .registerWriteHandler(new DefaultStyle())
                    .registerWriteHandler(new CustomCellWriteWeightConfig())
                    .registerWriteHandler(new CustomCellWriteHeightConfig())
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("sheet1")
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "导出失败" + e.getMessage());
            response.getWriter().println(map);
        }
    }

实体类

@Data
public class EntityVo{
    @ExcelProperty(value = "姓名", index = 0)
    private String A1;
    @ExcelProperty(value = "性别", index = 1)
    private String A2;
    @ExcelProperty(value = "年龄", index = 2)
    private String A3;
    @ExcelProperty(value = "爱好", index = 3)
    private String A4;
    @ExcelProperty(value = "颜色", index = 4)
    private String A5;
    @ExcelProperty(value = "介绍", index = 5)
    private String A6;
}
posted @ 2024-12-02 17:07  小海葵  阅读(7)  评论(0编辑  收藏  举报