需要的依赖
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>easyexcel</artifactId>
     <version>2.1.6</version>
 </dependency>
 <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml</artifactId>
     <version>3.17</version>
 </dependency>
 <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml-schemas</artifactId>
     <version>3.17</version>
 </dependency>
 <dependency>
     <groupId>org.apche.poi</groupId>
     <artifactId>poi</artifactId>
     <version>3.17</version>
 </dependency>
代码,根据使用的类型和list导出
public ResponseEntity promotionMonitorListDownload(PromotionMonitorQueryDTO queryDTO) {
    UserDTO currentUser = UserDTO.getCurrentUser();
    try {
        List<PromotionMonitorExcalInfo> list = promotionMonitorVOService.promotionMonitorListExcalDownload(currentUser, queryDTO);
        Integer todayInt = ZonedDateUtil.todayInt(ZonedDateUtil.TIMEZONE_ASIN_SHANGHAI);
        String fileName = new StringBuilder().append("deals管理_").append(todayInt).toString();
        return buildExportResponse(fileName,PromotionMonitorExcalInfo.class,list);
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResultBean.fail("系统错误"));
    }
}
//excal导出 private <T> ResponseEntity buildExportResponse(String fileName, Class<T> clazz, List<T> list) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); EasyExcel.write(outputStream,clazz).excelType(ExcelTypeEnum.XLSX).sheet(fileName).doWrite(list); String contentDisposition = "attachment;filename=".concat(URLEncoder.encode(fileName, "UTF-8")).concat(".xlsx"); Resource resource = genResource(outputStream); return ResponseEntity.status(HttpStatus.OK) .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(resource.contentLength())) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); } private Resource genResource(ByteArrayOutputStream outputStream) { Resource resource = null; try { resource = new ByteArrayResource(outputStream.toByteArray()); } finally { IOUtils.closeQuietly(outputStream); return resource; } }
使用的实体类上打好注解作为表头部分,例如
@Getter @Setter @AllArgsConstructor @NoArgsConstructor public class PromotionMonitorExcalInfo { @ExcelProperty("Deal ID") @ApiModelProperty(value = "Deal ID") private String dealID;private String dealPrice; @ExcelProperty("时间") @ApiModelProperty(value = "时间") private String ntime; @ExcelProperty("Sales") @ApiModelProperty(value = "Sales") private String trustee; @ExcelProperty("创建时间") @ApiModelProperty(value = "创建时间") private String createTimeFormat; }
原文:https://www.cnblogs.com/badfisher/p/15060834.html