业务场景
一些导出功能的导出列需要根据不同的条件动态导出
实现方案
增加导出工具类
public class ExportUtil {
public static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
workbook.write(response.getOutputStream());
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Excel 类型枚举
*/
enum ExcelTypeEnum {
XLS("xls"), XLSX("xlsx");
private String value;
ExcelTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
增加导出接口
@GetMapping("dynamicExport")
public void dynamicExport(HttpServletResponse response) {
Map<String, Object> map = new HashMap<>();
map.put("one", "1");
map.put("two", "2");
map.put("three", "3");
map.put("four", "4");
Map<String, Object> map1 = new HashMap<>();
map1.put("one", "11");
map1.put("two", "21");
map1.put("three", "31");
map1.put("four", "41");
//maps 存储数据
List<Map<String, Object>> maps = new ArrayList<>();
maps.add(map);
maps.add(map1);
//entityList 存表头
List<ExcelExportEntity> entityList = new ArrayList<>();
entityList = getEntityList();
Workbook workbook = ExcelExportUtil.exportExcel(
new ExportParams("test", "testName", ExcelType.HSSF)
, entityList
, maps);
ExportUtil.downLoadExcel("学生列表", response, workbook);
}
private List<ExcelExportEntity> getEntityList() {
List<ExcelExportEntity> entityList = new ArrayList<>();
entityList.add(new ExcelExportEntity("姓名", "one", 20));
entityList.add(new ExcelExportEntity("年龄", "two", 20));
entityList.add(new ExcelExportEntity("地址", "three", 20));
entityList.add(new ExcelExportEntity("日期", "four", 20));
return entityList;
}