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. PHP cal_info() 函数

    ------------恢复内容开始------------ 实例 返回格利高里历法的信息: <?phpprint_r(cal_info(0));?> 运行实例 » 定义和用法 cal_i ...

  2. PHP empty() 函数

    empty() 函数用于检查一个变量是否为空.高佣联盟 www.cgewang.com empty() 判断一个变量是否被认为是空的.当一个变量并不存在,或者它的值等同于 FALSE,那么它会被认为不 ...

  3. 6.18 省选模拟赛 树 倍增 LCT

    LINK:树 考虑暴力 保存每个版本的父亲 然后暴力向上跳.得分20. 考虑离线 可以离线那么就可以先把树给搞出来 然后考虑求k级祖先 可以倍增求. 如何判断合法 其实要求路径上的边的时间戳<= ...

  4. 牛客练习赛63 牛牛的斐波那契字符串 矩阵乘法 KMP

    LINK:牛牛的斐波那契字符串 虽然sb的事实没有改变 但是 也不会改变. 赛时 看了E和F题 都不咋会写 所以弃疗了. 中午又看了一遍F 发现很水 差分了一下就过了. 这是下午和古队长讨论+看题解的 ...

  5. Hadoop学习之第一个MapReduce程序

    期望 通过这个mapreduce程序了解mapreduce程序执行的流程,着重从程序解执行的打印信息中提炼出有用信息. 执行前 程序代码 程序代码基本上是<hadoop权威指南>上原封不动 ...

  6. 使用docker安装nginx并配置端口转发

    使用docker安装并运行nginx命令: docker run --name=nginx -p 80:80 -d docker.io/nginx 使用命令: docker exec -it ngin ...

  7. 网络安全传输系统-sprint1传输子系统

    一.产品规划与设计 二.传输子系统 基本框架:(1)不带安全功能的传输系统 (2)安全加密功能 part1:基本传输子程序设计(不带安全加密功能) 客户端 服务器 int main(int argc, ...

  8. Android——对话框的全部内容。(课堂总结)

    前面的总结是写过对话框的,但是那只是冰山一角,简单的创建和使用罢了. 今天具体讲下AlertDialog. 首先对话框不需要在布局里写,在活动里new出来的. AlertDialog.Builder ...

  9. Android Studio简单的登陆界面

    在app->src->main->java里面找到MainActivity.java,将鼠标放到activity-main上按住Ctrl后单击跳转到activity-main.xml ...

  10. MyFirstJavaWeb

    源代码: Register.jsp <%@ page language="java" contentType="text/html; charset=utf-8&q ...