1.先引入hutool的相关依赖
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.4</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2.导出
创建一个Controller进行测试
@GetMapping(path = "/export")
public void export(HttpServletResponse response,OrderPageRequest orderPageRequest)throws IOException { {
// 查询导出订单数据
List<OrdereExportView> ordereList = getOrdereList(orderPageRequest);
if (CollectionUtils.isEmpty(ordereList)) {
throw new BusinessException("暂无数据!");
}
//在内存操作,写到浏览器
ExcelWriter writer = ExcelUtil.getWriter(true);
//自定义标题别名
writer.addHeaderAlias("orderCode", "订单编码");
writer.addHeaderAlias("addressName", "送达方名称");
writer.addHeaderAlias("amount", "订单金额");
writer.addHeaderAlias("orderStatusDesc", "订单状态");
writer.addHeaderAlias("createTime", "创建时间");
writer.addHeaderAlias("submitTime", "提交时间");
writer.addHeaderAlias("createTime", "创建时间");
//只保留别名的数据
writer.setOnlyAlias(true);
// 默认配置
writer.write(ordereList, true);
// 设置content—type
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
// 设置标题
String fileName = URLEncoder.encode("订单导出", "UTF-8");
//Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
ServletOutputStream outputStream = response.getOutputStream();
//将Writer刷新到OutPut
writer.flush(outputStream, true);
outputStream.close();
writer.close();
}
3.导出效果