EasyExcel Demo

实体类

    /**
     * 排班日期,主键
     */
    @TableId
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
    @ExcelProperty(value = "值班日期",converter = LocalDateConverter.class)
    private LocalDate dutyTime;

    /**
     * 值班人员id
     */
    @ExcelProperty("值班人员id")
    private String dutyUser;

    /**
     * 播音人员id
     */
    @ExcelProperty("播音人员id")
    private String broadcastUser;

    /**
     * 是否节假日,1是,0否
     */
    @ExcelProperty("是否节假日")
    private Boolean holiday;

类型转换

public class LocalDateConverter implements Converter<LocalDate> {

    @Override
    public Class<LocalDate> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) {
        return LocalDateTimeUtil.parseDate(cellData.getStringValue(), "yyyy-MM-dd");
    }

    @Override
    public CellData<String> convertToExcelData(LocalDate localDate, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) {
        return new CellData<>(LocalDateTimeUtil.format(localDate, "yyyy-MM-dd"));
    }
}

excel下载

    @ApiOperation("值班情况按时间段导出(值班)")
    @RequestMapping(value = "excel", method = RequestMethod.GET)
    public void excel(String startDay, String endDay, HttpServletResponse response) {
        List<InfoScheduling> infoSchedulings = infoSchedulingService.findByTimeRange(startDay, endDay);
        String fileName = "值班情况" + startDay + "至" + endDay;
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(getOutputStream(fileName, response), InfoScheduling.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("值班情况").build();
            excelWriter.write(infoSchedulings, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }
原文地址:https://www.cnblogs.com/unique1319/p/13841794.html