导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
建立excel表格所需数据类(载入excel表的数据)
ExcelProperty 可定义列名,位置等属性
@Data
@ExcelIgnoreUnannotated
public class OrderListResp {
@ApiModelProperty("用户id")
@ExcelProperty(value = "用户ID", index = 0)
private Long userId;
}
定义controller类
OrderListReq 由自己定义前端传来的参数,Request为自定义包装类
@ApiOperation("订单列表导出")
@PostMapping("/downLoad")
public void orderListExport(@Validated @RequestBody Request<OrderListReq> request, HttpServletResponse response) throws IOException {
orderService.orderListExport(request.getData(), response);
}
具体实现流程为:格式设置-拼装数据-写出
@Override
public void orderListExport(OrderListReq data, HttpServletResponse response) throws IOException {
String filename = "订单列表";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
List<OrderListResp> orderListResps = orderRecordMapper.orderListExport(data);
OutputStream outputStream = response.getOutputStream();
EasyExcel.write(outputStream, OrderListResp.class)
.registerWriteHandler(new SimpleColumnWidthStyleStrategy(20))
.sheet("订单列表")
.doWrite(orderListResps);
outputStream.flush();
outputStream.close();
}
结果展示
本文只实现简单的文件导出,若需标红,合并,字体颜色等,可设置自定义格式类并进行配置。注意(请求类,写入表格类和方法调用需自行写入)