vue实现下载excel表格
据我了解的前端的下载方式有三种,第一种是通过a标签来进行下载,第二种时候通过window.location来下载,第三种是通过请求后台的接口来下载,今天就来记录一下这三种下载方式。
方法一:通过a标签
// href为文件的存储路径或者地址,download为问文件名
<a href="/images/logo.jpg" download="logo" />
1
2
优点:简单方便。
缺点:这种下载方式只支持Firefox和Chrome不支持IE和Safari,兼容性不够好。
方法二:通过window.location
window.location = 'http://127.0.0.1:8080/api/download?name=xxx&type=xxx'
1
优点:简单方便。
缺点:只能进行get请求,当有token校验的时候不方便。
方法三:通过请求后台接口
// download.js
import axios from 'axios'
export function download(type, name) {
axios({
method: 'post',
url: 'http://127.0.0.1:8080/api/download',
// headers里面设置token
headers: {
loginCode: 'xxx',
authorization: 'xxx'
},
data: {
name: name,
type: type
},
// 二进制流文件,一定要设置成blob,默认是json
responseType: 'blob'
}).then(res => {
const link = document.createElement('a')
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.setAttribute('download', `${name}.xlsx`)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// download.java
@RequestMapping(value = "/api/download",produces = "application/octet-stream", method = RequestMethod.POST)
public void downloadTemplate(@RequestBody Map<String,Object> paramsMap, HttpServletResponse response) {
try {
if (paramsMap.get("type").equals("xxx") && paramsMap.get("name").equals("xxx")) {
String[] str = new String[]{"区县","所属省份","所属地市"};
Workbook workbook = ExportExcel.exportExcel("行政区划表模版", str, null, "yyyy-MM-dd");
download(response, workbook, "CityDict");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void download(HttpServletResponse response, Workbook workbook, String fileName) {
try {
response.setContentType("application/octet-stream;charset=UTF-8;");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xlsx");
ByteArrayOutputStream by = new ByteArrayOutputStream();
OutputStream osOut = response.getOutputStream();
// 将指定的字节写入此输出流
workbook.write(osOut);
// 刷新此输出流并强制将所有缓冲的输出字节被写出
osOut.flush();
// 关闭流
osOut.close();
} catch (IOException e) {
LogUtils.getExceptionLogger().info("下载模板错误:{}", e.getMessage());
}
}
————————————————
原文链接:https://blog.csdn.net/aSmallProgrammer/article/details/91440793