导出Execl(vue 2.x + spring mvc)

最近项目中用到了导出功能特此记录。

写入Execl采用的EasyExcel工具,文档:https://www.yuque.com/easyexcel/doc/easyexcel

1.添加EasyExecl依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.0.5</version>
</dependency>

2.实现Controller

 /**
     * 文件下载(失败了会返回一个有部分数据的Excel)
     * <p>1. 创建excel对应的实体对象 参照{@link DownloadData}
     * <p>2. 设置返回的 参数
     * <p>3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
    }

3.项目中添加下载方法(前端)

export function download(data) {
  return axios({
    url: '/download',
    method: 'get',
    data: data,
    responseType: 'blob'
  })
}

4.response interceptor 添加blob返回类型处理

service.interceptors.response.use(response => {
    const res = response.data
    if(response.config.responseType == 'blob'){
        const disposition = response.headers['content-disposition'];
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(disposition);
        const filename = matches[1].replace(/['"]/g, '');
        return {data:res, fileName:decodeURIComponent(filename)};
    }
   ...
}

5.下载按钮绑定 onDownload 方法

<a-button type="primary" html-type="submit" icon="download" @click="onDownload">导出</a-button>

5.下载文件

onDownload(){
    download().then(res => {
        var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //type这里表示xlsx类型
        var downloadElement = document.createElement('a');
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = res.fileName; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象 
    }).catch(err => {
        //此处是 ant design 全局提示方法
        this.$message.error('导出数据失败');
    });
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。