spring boot axios导出CSV文件
引言
小编是一个比较喜欢研究的人,项目中经常需要导出附件的操作,前端时间一直想仔细研究,尝试了几次都没成功,这次项目开发有大量的导出操作,所以小编不得不静下心来仔细研究研究。
本次研究小编一共研究了CSV,xls,xlsx文件的导出操作。话不多说,直接上代码,希望对您有帮助。
开发环境
后端: Spring boot
前端: vue axios
前端界面
三个按钮分别代表三个不同的类型文件的导出操作,分别是CSV,excel03,excel07
前端代码
<template>
<div>
<el-button type="primary" @click="csv">csv</el-button>
<el-button type="primary" @click="excel03">excel03</el-button>
<el-button type="primary" @click="excel07">excel07</el-button>
</div>
</template>
<script>
import pageApi from '../../../../api/pageApi'
export default {
name: "filedown",
methods:{
csv(){
pageApi.csv().then(res => { //res为axios请求返回的未被本地代码处理过的对象
//注意这里是new Blob([res.data])
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', `1.csv`)
document.body.appendChild(link)
link.click()
})
},
excel03(){
pageApi.exc03().then(res => { //res为axios请求返回的未被本地代码处理过的对象
//注意这里是new Blob([res.data])
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
//注意这里是1.xls` 名称可变,可以根据后端的参数来变化
link.setAttribute('download', `1.xls`)
document.body.appendChild(link)
link.click()
})
},
excel07(){
pageApi.exc07().then(res => { //res为axios请求返回的未被本地代码处理过的对象
//注意这里是new Blob([res.data])
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = url
//注意这里是1.xlsx` 名称可变,可以根据后端的参数来变化
link.setAttribute('download', `1.xlsx`)
document.body.appendChild(link)
link.click()
})
}
}
}
</script>
<style scoped>
</style>
前端的下载代码网上很多,大都是千篇一律,但是都能实现类似以标签的操作。
axios 的api配置
//导出csv文件不需要配置responseType
csv(){
return new Promise(function (resolve, reject) {
axios.post('/DownloadController/CSV', {})
.then((res) => {
resolve(res)
})
.catch((error) => {
reject(error)
})
})
},
//导出exc03文件不需要配置responseType 为 arraybuffer ,设置为其他界面会出现乱码
exc03(){
return new Promise(function (resolve, reject) {
let myAxios = axios.create({
responseType: 'arraybuffer'
})
myAxios.post('/DownloadController/exc03', {})
.then((res) => {
resolve(res)
})
.catch((error) => {
reject(error)
})
})
},
//导出exc07文件不需要配置responseType 为 arraybuffer ,设置为其他界面会出现乱码
exc07(){
return new Promise(function (resolve, reject) {
let myAxios = axios.create({
responseType: 'arraybuffer'
})
myAxios.post('/DownloadController/exc07', {})
.then((res) => {
resolve(res)
})
.catch((error) => {
reject(error)
})
})
}
后端代码
p
ackage com.frame.demo.web.controller;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @version V1.0
* @Author llt
* @Mail liulangtao@boco.com.cn
* @Date 2019-10-16 15:17
* @description
***/
@RequestMapping("/DownloadController")
@Api(value = "附件下载")
@RestController
public class DownloadController {
@Resource
private ResourceLoader resourceLoader;
导出csv后端代码
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/CSV", method = { RequestMethod.POST,RequestMethod.GET}) // postman,url,3.tbox请求下载文件,暂时只支持单文件下载。
public void getCSV(HttpServletRequest request, HttpServletResponse response){
String fileName ="1.csv";
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
String path = "source" + File.separator + fileName;
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+path);
response.setContentType("application/octet-stream");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("Pragma", "no-cache");
inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
}
导出03版excel后端代码
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/exc03", method = { RequestMethod.POST,RequestMethod.GET}) // postman,url,3.tbox请求下载文件,暂时只支持单文件下载。
public void getExcel03(HttpServletRequest request, HttpServletResponse response){
String fileName ="1.xls";
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
String path = "source" + File.separator + fileName;
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+path);
response.setContentType("application/octet-stream");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("Pragma", "no-cache");
inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
}
导出07版excel后端代码
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/exc07", method = { RequestMethod.POST,RequestMethod.GET}) // postman,url,3.tbox请求下载文件,暂时只支持单文件下载。
public void getExcel07(HttpServletRequest request, HttpServletResponse response){
String fileName ="1.xlsx";
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
String path = "source" + File.separator + fileName;
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+path);
response.setContentType("application/octet-stream");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("Pragma", "no-cache");
inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
总共研究了导出三类文件,其实后端的代码都是一样的,除了导出的文件不同,全部粘贴上的目的是为了让使用的同学看的更加清楚,少走弯路。希望对您有帮助。
运行结果
csv文件:
excel03文件:
excel07文件:
错误情况
返回的结果里面出现了乱码,此致情况通常是由于你请求时候axios的response设置的错误或者没有设置 responseType为arraybuffer。
axios的responseType设置方式是:
let myAxios = axios.create({
responseType: ‘arraybuffer’
})
正确情况res返回的截图
注意截图中的红色标注的地方:正确返回时候是一个arraybuffer对象,说明设置了responseType为arraybuffer