后端代码:
首先是引入依赖:
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
然后是生成实体类,注意@Excel的使用,这里
import cn.afterturn.easypoi.excel.annotation.Excel;
import jdk.nashorn.internal.objects.annotations.Getter;
import jdk.nashorn.internal.objects.annotations.Setter;
import java.util.Date;
public class ExportVo {
@Excel(name="用户名")
private String userName;
@Excel(name="日期")
private Date createTime;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
逻辑代码:
@PostMapping("/exportTest")
public void exportTest(HttpServletResponse response)throws Exception{
List<ExportVo> vos = new ArrayList<>();
ExportVo vo1 = new ExportVo();
vo1.setUserName("aa");
vo1.setCreateTime(new Date());
vos.add(vo1);
exportExcel(response,"testExcel",ExportVo.class,vos);
}
public void exportExcel(HttpServletResponse response,String outputName,Class<?> clazz,List<?> list)throws Exception{
String filename = URLEncoder.encode(outputName,"UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
response.addHeader("Access-Control-Expose-Methods","GET,POST,PUT,DELETE,OPTIONS");
response.addHeader("Access-Control-Allow-Headers","Content-Type,X-Requested-With,accept,Origin," +
"Access-Control-Request-Method,Access-Control-Request-Headers,token");
ExportParams exportParams = new ExportParams();
exportParams.setType(ExcelType.XSSF);
Workbook workbook = exportExcel(exportParams,clazz,list);
ServletOutputStream os = response.getOutputStream();
workbook.write(os);
os.close();
}
private Workbook exportExcel(ExportParams entity, Class<?> pojoClass, Collection<?> dataSet){
Workbook workbook = new SXSSFWorkbook(100);
ExcelExportService excelExportService = new ExcelExportService();
excelExportService.createSheet(workbook,entity,pojoClass,dataSet);
return workbook;
}
效果图:
前端代码:
添加按钮和点击事件:
<el-button type="danger" @click="exportTest">导出测试</el-button>
方法:
async exportTest(){
const response = await axios.post('http://127.0.0.1:9999/import/exportTest',null,{responseType:'blob'})
const blob = new Blob([response.data],{type:'application/vnd.ms-excel'})
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = '导出.xlsx'
document.body.appendChild(link)
link.click();
document.body.removeChild(link)
URL.revokeObjectURL(url)
}
最后成功导出
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。