Vue + axios + SpringBoot 2实现导出Excel

1. 前端js代码-发送Http请求

/**
* 文件下载
* @param url 下载地址
* @param fileName 文件名称
* @param params 参数
*/
downloadFile: function (url, params) {
params = params || {}
let httpService = axios.create({
timeout: 300000, // 请求超时时间
headers: {
'Cache-Control': 'no-cache'
}
})
return httpService({
method: 'POST',
url: url,
data: params,
responseType: 'blob'
}).then(res => {
return res.data
})
},
/**
*文件上传
* @param url 上传地址
* @param file 文件对象 target.files <input type='file'> 的文件对象
* @param params 参数可以添加fileName ,type等等
* @returns {Promise<AxiosResponse | never>}
*/
uploadFile: function (url, file, params) {
const formData = new FormData()
params = params || {}
Object.keys(params).map(key => {
formData.append(key, params[key])
})
formData.append('type', params['type'] || 'ReadExcel')
formData.append(params['fileName'] || 'file', file)
let httpService = axios.create({
timeout: 300000, // 请求超时时间
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'multipart/form-data'
}
})
return httpService.post( url, formData).then(res => {
return res.data
})
}

2. 前端js代码-处理后端返回的流数据(通用处理二进制文件的方法,而不仅仅针对Excel)

/**
@resData 后端响应的流数据
@fileName 文件名称 如果后端设置的是xls/xlsx与后端文件后缀一致。
**/
function dealDownLoadData(resData,fileName){
try { let blob ;
if(resData instanceof Blob){
blob = resData;
}else{
blob = new Blob([resData], { type: resData.type});
}
if (!!window.ActiveXObject || "ActiveXObject" in window) { //IE浏览器
//navigator.msSaveBlob(blob, fileName); //只有保存按钮
navigator.msSaveOrOpenBlob(blob, fileName); //有保存和打开按钮
}else{
var linkElement = document.createElement('a');
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", fileName);
var clickEvent = new MouseEvent("click",
{
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
}
} catch (ex) {
console.log(ex);
} }

3.导出Excel

/**
* 导出Excel
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/xxx")
public ResponseEntity<Resource> downloadFileApi() throws Exception {
//Excel场景一:直接创建,然后编辑内容
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); //Excel场景二:读取模板,然后在模板中编辑内容
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream("/template.xls"));
hssfWorkbook = new HSSFWorkbook(poifsFileSystem); //写到输出流中
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
hssfWorkbook.write(outputStream);
//文件名称:注意:这里的后缀名称必须是xls或 xlsx,不然不能识别为excel
String fileName = "xxx.xls";
//返回
ByteArrayInputStream is = new ByteArrayInputStream(outputStream.toByteArray());
//调用通用下载文件方法
return this.downloadFile(is, fileName); }
/**
* 通用的下载方法,可以下载任何类型文件
* @param is
* @param fileName
* @return
* @throws IOException
*/
public ResponseEntity<Resource> downloadFile(InputStream is,String fileName) throws IOException{ HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("charset", "utf-8");
//设置下载文件名
headers.add("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
Resource resource = new InputStreamResource(is);
return ResponseEntity.ok()
.headers(headers)
//根据文件名称确定文件类型。
.contentType(MediaType.parseMediaType(HttpKit.getMimeType(fileName)))
.body(resource);
}

Vue + axios + SpringBoot 2实现导出Excel的更多相关文章

  1. SpringBoot使用Easypoi导出excel示例

    SpringBoot使用Easypoi导出excel示例 https://blog.csdn.net/justry_deng/article/details/84842111

  2. Vue框架下实现导入导出Excel、导出PDF

    项目需求:开发一套基于Vue框架的工程档案管理系统,用于工程项目资料的填写.编辑和归档,经调研需支持如下功能: Excel报表的导入.导出 PDF文件的导出 打印表格 经过技术选型,项目组一致决定通过 ...

  3. VUE中使用XLSX实现导出excel表格

    简介 项目中经常会用导出数据的场景,这里介绍 VUE 中如何使用插件 xlsx 导出数据 安装 ## 1.使用 npm 或 yarn 安装依赖(三个依赖) npm install -S file-sa ...

  4. Vue通过Blob对象实现导出Excel功能

    不同的项目有不同的导出需求,有些只导出当前所显示结果页面的表格进入excel,这个时候就有很多插件,比如vue-json-excel或者是Blob.js+Export2Excel.js来实现导出Exc ...

  5. springboot通过poi导出excel

    Maven引入依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi< ...

  6. Vue项目中将table组件导出Excel表格以及打印页面内容

    体验更优排版请移步原文:http://blog.kwin.wang/programming/vue-table-export-excel-and-print.html 页面中显示的table表格,经常 ...

  7. # vue 如何通过前端来导出excel表格

    在做一些简单的demo时,偶尔会遇到导出excel表格.如果请后端帮忙的话 比较浪费时间,那么前端如何导出excel表格,下面就来记录一下之前使用到的案例 一.安装依赖 npm i file-save ...

  8. SpringBoot之导入导出Excel

    1.添加springBoot支持 <dependency> <groupId>org.apache.poi</groupId> <artifactId> ...

  9. vue axios springBoot 跨域session丢失

    前端: 在引入axios的地方配置 axios.defaults.withCredentials=true,就可以允许跨域携带cookie信息了,这样每次发送ajax请求后,只要不关闭浏览器,得到的s ...

随机推荐

  1. 求100以内所有奇数的和,存于字变量X中。

    问题 求100以内所有奇数的和,存于字变量X中. 代码 data segment x dw ? data ends stack segment stack db 100 dup(?) stack en ...

  2. Python File next() 方法

    概述 next() 方法在文件使用迭代器时会使用到,在循环中,next()方法会在每次循环中调用,该方法返回文件的下一行,如果到达结尾(EOF),则触发 StopIteration高佣联盟 www.c ...

  3. luogu P3829 [SHOI2012]信用卡凸包 凸包 点的旋转

    LINK:信用卡凸包 当 R==0的时候显然是一个点的旋转 之后再求凸包即可. 这里先说点如何旋转 如果是根据原点旋转的话 经过一个繁杂的推导可以得到一个矩阵. [cosw,-sinw] [sinw, ...

  4. EC R 86 D Multiple Testcases 构造 贪心 二分

    LINK:Multiple Testcases 得到很多种做法.其中O(n)的做法值得一提. 容易想到二分答案 check的时候发现不太清楚分配的策略. 需要先考虑如何分配 容易发现大的东西会对小的产 ...

  5. 4.9 省选模拟赛 划分序列 二分 结论 树状数组优化dp

    显然发现可以二分. 对于n<=100暴力dp f[i][j]表示前i个数分成j段对于当前的答案是否可行. 可以发现这个dp是可以被优化的 sum[i]-sum[j]<=mid sum[i] ...

  6. PHP开发者该知道的多进程消费队列

    引言 最近开发一个小功能,用到了队列mcq,启动一个进程消费队列数据,后边发现一个进程处理不过来了,又加了一个进程,过了段时间又处理不过来了… 这种方式每次都要修改crontab,如果进程挂掉了,不会 ...

  7. 深入探究JVM之类加载与双亲委派机制

    @ 目录 前言 类的生命周期 加载 验证 准备 解析 初始化 案例一 案例二 案例三 案例四 类加载器 类加载器和双亲委派模型 破坏双亲委派模型 第一次 SPI Tomcat OSGI 总结 前言 前 ...

  8. 使用Flask开发简单接口(4)--借助Redis实现token验证

    前言 在之前我们已开发了几个接口,并且可以正常使用,那么今天我们将继续完善一下.我们注意到之前的接口,都是不需要进行任何验证就可以使用的,其实我们可以使用 token ,比如设置在修改或删除用户信息的 ...

  9. 高效c/c++日志工具zlog使用介绍

    1. zlog简介 zlog的资料网上很多,这里不在详细说明:zlog是用c写的一个日志工具,非常小,而且高效,可以同时向控制台和文件中输出,日志接口与printf使用基本一样,所以使用起来很简单. ...

  10. vue中methods互相调用的方法

    a:function(goods) { this.aa= []; this.bb= 0; this.cc= 0; }, b:function(){ if(this.bbb!= 0){ this.aa= ...