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. Python continue语句

    Python continue语句: 当执行到 continue 语句时,将不再执行本次循环中 continue 语句接下来的部分,而是继续下一次循环. lst = [7,8,9,4,5,6] for ...

  2. Seaborn基础3

    import seaborn as sns import numpy as np import matplotlib.pyplot as plt sns.set(rc = {"figure. ...

  3. PHP curl_multi_remove_handle函数

    (PHP 5) curl_multi_remove_handle — 移除curl批处理句柄资源中的某个句柄资源 说明 int curl_multi_remove_handle ( resource ...

  4. MySQL一主多从配置和读写分离配置

    一.一主多从配置 此次操作实现的是一主两从的方式.主服务器slave2(2.100),从服务器slave2-1(2.107),slave2-2(2.108);第一:准备主数据库    1. 在不同的机 ...

  5. Redis实现商品热卖榜

    Redis系列 redis相关介绍 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合 ...

  6. windows下使用redis命令行模式查询数据

    背景:redis的火,就像java一样,对于测试人员来说,使用它就需要好好搞下,现在就整理下命令行模式,来查询获取自己想要的值: 命令行连接命令:redis-cli -h 主机名 -p 端口号 -a ...

  7. Spring 基于注解的 IOC 配置

    创建 spring 的 的 xml 配置 文件 <context:component-scan base-package="com.itheim"/> 指定创建容器时要 ...

  8. C# Hello Word

    不管学习什么语言,第一个例子绝对是一个经典的HelloWorld程序那么接下来我们使用 vs studio 2019 来创建一个 HelloWorld 程序 启动vs2019选择 文件-新建-项目-新 ...

  9. .Net Core HttpClient处理响应压缩

    前言     在上篇文章[ASP.NET Core中的响应压缩]中我们谈到了在ASP.NET Core服务端处理关于响应压缩的请求,服务端的主要工作就是根据Content-Encoding头信息判断采 ...

  10. U盘数据泄露,用不到30行的Python代码就能盗走

    今天跟大家分享下一段简单的代码,希望能给经常用U盘的人警戒,提高信息安全意识. 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做 ...