1. 程式人生 > >easypoi實現快速匯出

easypoi實現快速匯出

匯入依賴
<!--EasyPoi-->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>3.0.3</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>3.0.3</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>3.0.3</version>
</dependency>

避免重複程式碼,做一個工具類

public class ExcelUtil {

    public static void addExcelList(List<Map<String, Object>> excelList, ExportParams exportParams, Class<?> cls, List<?> list) {
        HashMap<String, Object> 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<Map<String, Object>> getExcelExport(PageForm form) {
        ExportParams exportParams = new ExportParams();
        List<Map<String, Object>> 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/