easypoi实现快速导出

导入依赖


    cn.afterturn
    easypoi-base
    3.0.3


    cn.afterturn
    easypoi-web
    3.0.3


    cn.afterturn
    easypoi-annotation
    3.0.3

避免重复代码,做一个工具类

public class ExcelUtil {

    public static void addExcelList(List> excelList, ExportParams exportParams, Class cls, List list) {
        HashMap reportMap = new HashMap<>(16);
        reportMap.put("title", exportParams);
        reportMap.put("entity", cls);
        reportMap.put("data", list);
        excelList.add(reportMap);
    }

    public static KeyValue getExcelStream(HttpServletResponse response, Workbook workbook) throws IOException {
        try (ServletOutputStream out = response.getOutputStream()) {
            workbook.write(out);
            return KeyValue.ok("导出成功");
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException(e);
        }
    }
}

相关实现:

@RestController
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private ExcelService excelServiceImpl;

    @GetMapping("/export")
    public KeyValue excelExport(@Validated  PageForm form, HttpServletResponse response, BindingResult bindingResult)throws IOException {
        String fileName = new String("excel导出_".getBytes("UTF-8"),"ISO-8859-1");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename= "+fileName+ LocalDate.now().toString()+".xls");
        Workbook workbook = ExcelExportUtil.exportExcel(excelServiceImpl.getExcelExport(form), ExcelType.HSSF);
        workbook.setSheetName(0, "sheet名字");
        return ExcelUtil.getExcelStream(response, workbook);
    }

}
@Service
public class ExcelServiceImpl implements ExcelService {

    @Override
    public List> getExcelExport(PageForm form) {
        ExportParams exportParams = new ExportParams();
        List> excelList = new ArrayList<>();
        ExcelExportVo demo1 = ExcelExportVo.builder().name("测试1").date(new Date()).sex(1).build();
        ExcelExportVo demo2 = ExcelExportVo.builder().name("测试2").date(new Date()).sex(2).build();
        ExcelUtil.addExcelList(excelList, exportParams, ExcelExportVo.class, Lists.newArrayList(demo1,demo2));
        return excelList;
    }
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ExcelExportVo {

    @Excel(name = "姓名")
    private String name;

    @Excel(name = "性别",replace = {"男_1","女_2"})
    private Integer sex;

    @Excel(name = "日期", format = "yyyy-MM-dd")
    private Date date;
}

其他easypoi用法:http://easypoi.mydoc.io/

 

你可能感兴趣的:(spring,boot)