diff --git a/epdc-commons-tools/src/main/java/com/elink/esua/epdc/commons/tools/utils/ExcelUtils.java b/epdc-commons-tools/src/main/java/com/elink/esua/epdc/commons/tools/utils/ExcelUtils.java index 5a3d356..6fccf45 100644 --- a/epdc-commons-tools/src/main/java/com/elink/esua/epdc/commons/tools/utils/ExcelUtils.java +++ b/epdc-commons-tools/src/main/java/com/elink/esua/epdc/commons/tools/utils/ExcelUtils.java @@ -10,8 +10,10 @@ package com.elink.esua.epdc.commons.tools.utils; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; +import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; import cn.afterturn.easypoi.excel.export.ExcelBatchExportService; import cn.afterturn.easypoi.handler.inter.IExcelExportServer; +import com.elink.esua.epdc.commons.tools.exception.RenException; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; @@ -167,6 +169,66 @@ public class ExcelUtils { return ""; } + /** + * Excel导出,先sourceList转换成List,再导出 + * + * @param response response + * @param fileName 文件名 + * @param sourceList 原数据List + * @param sheetNames sheet名字列表 + */ + public static void exportExcelToTargetWithSheets(HttpServletResponse response, String fileName, List sheetNames, + List> targetClassList,Collection... sourceList) throws Exception { + if(sheetNames.size()!=targetClassList.size() && targetClassList.size()!=sourceList.length){ + throw new RenException("参数传递出错"); + } + // 将sheets使用得map进行包装 + List> sheetsList = new ArrayList<>(); + for (int i = 0;i deptDataMap = new HashMap<>(4); + ExportParams exportParams = new ExportParams(); + exportParams.setSheetName(sheetNames.get(i)); + deptDataMap.put("title", exportParams); + // 模版导出对应得实体类型 + deptDataMap.put("entity", targetClassList.get(i)); + // sheet中要填充得数据 + deptDataMap.put("data", sourceList[i]); + sheetsList.add(deptDataMap); + } + exportExcelWithSheets(response,fileName,sheetsList); + + } + + /** + * 多sheetExcel导出 + * + * @param response response + * @param fileName 文件名 + * @param sheetsList 多sheet组装 + */ + public static void exportExcelWithSheets(HttpServletResponse response, String fileName, List> sheetsList) throws IOException { + + if(StringUtils.isBlank(fileName)){ + //当前日期 + fileName = DateUtils.format(new Date()); + } + Workbook workbook = null; + try { + workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF); + } catch (Exception ex) { + workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.XSSF); + } + + response.setCharacterEncoding("UTF-8"); + response.setHeader("content-Type", "application/vnd.ms-excel"); + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls"); + ServletOutputStream out = response.getOutputStream(); + workbook.write(out); + out.flush(); + out.close(); + } + /** * 验证EXCEL文件 *