1、springboot后端
注:后端导出excel使用的是easypoi插件实现
1、实体类
package com.springbootapi.entity;
import cn.afterturn.easypoi.excel.annotation.Excel;
public class EasyPoiExport {
@Excel(name = "名字", width = 30)
private String name;
@Excel(name = "年龄", width = 30)
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
2、控制层
@PostMapping("/excelExport")
public void excelExport(@RequestBody Map<String, String> person, HttpServletResponse response) throws Exception {
List<EasyPoiExport> result = new ArrayList<>();
EasyPoiExport easyPoiExport = new EasyPoiExport();
easyPoiExport.setName(person.get("name"));
easyPoiExport.setAge(22);
result.add(easyPoiExport);
result.add(easyPoiExport);
String title = "导出excel";
try {
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title, "UTF-8"));
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("导出", "sheet"), EasyPoiExport.class, result);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2、vue前端
- api
import request from './index'
function excelExport(name) {
let data = {
name
}
const result = request({
url: '/easyPoiExport/excelExport',
method: 'post',
responseType: 'blob',
data
})
return result
}
export default {
excelExport
}
2、dowload方法
export function download(data,fileName){
if(!data){
return
}
let url = window.URL.createObjectURL(new Blob([data],{type:'application/vnd.ms-excel'}))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
3、vue页面调用api获取后台数据,调用dowload方法导出excel
<template>
<div class=''>
<el-button @click="excelExport">导出</el-button>
</div>
</template>
<script>
import API from '@/api/requestMethods'
import { download } from '@/utils'
export default {
name: 'easypoiExport',
data() {
return {
}
},
methods: {
excelExport() {
API.excelExport('test').then(res => {
let fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
download(res.data, fileName)
}).catch(e => {
this.$message.error(`error:${e.message}`)
})
}
}
}
</script>
注:mock模块会影响原生的axios请求,使得服务器返回的blob类型变成乱码,导出的数据变为乱码。如果项目使用了mock需关闭mock。