POI導出Excel一招喫遍天下

maven依賴

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.9</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.9</version>
</dependency>

ExportUtil工具類

public class ExportUtil {

    /**
     *
     *@category 導出excel工具類
     * 2007,最高可支持100萬行數據
     *@date 2016年6月25日 下午7:49:54
     */
    public static void exportExcel(List<String> titles,List<Map<String, Object>> excelDatas,OutputStream os, String str) {
        try {
            // HSSFWorkbook 97-2003 版本的 ,
            // XSSFWorkbook 2007以上版本的
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet(str);

            if(titles != null && titles.size() > 0) {
                int r = 0;
                int columnNum = titles.size();
                Row titleRow = sheet.createRow(r++);
                CellStyle cellStyle = getTitleStyle(workbook);
                for(int i = 0; i < columnNum; i++) {
                    Cell titleCell = titleRow.createCell(i);
                    titleCell.setCellValue(titles.get(i));
                    titleCell.setCellStyle(cellStyle);
                }

                CellStyle contentStyle=getContentStyle(workbook);
                // 對excelDatas數據進行處理
                if(excelDatas != null && excelDatas.size() > 0) {
                    for(Map<String, Object> map : excelDatas) {
                        Row row = sheet.createRow(r++);// 數據行
                        for(int j = 0; j < columnNum; j++) {
                            Cell cell = row.createCell(j);
                            Object val=map.get(titles.get(j));
                            if (val == null){
                                cell.setCellValue("");
                            } else if (val instanceof String) {
                                cell.setCellValue((String) val);
                            } else if (val instanceof Integer) {
                                cell.setCellValue((Integer) val);
                            } else if (val instanceof Long) {
                                cell.setCellValue((Long) val);
                            } else if (val instanceof Double) {
                                cell.setCellValue((Double) val);
                            } else if (val instanceof Float) {
                                cell.setCellValue((Float) val);
                            } else if (val instanceof Date) {
                                DataFormat format = workbook.createDataFormat();
                                contentStyle.setDataFormat(format.getFormat("yyyy/MM/dd"));
                                cell.setCellValue((Date) val);
                            }  else if (val instanceof BigDecimal) {
                                double doubleVal = ((BigDecimal) val).doubleValue();
                                DataFormat format = workbook.createDataFormat();
                                //此格式是貨幣格式
                                contentStyle.setDataFormat(format.getFormat("#,##0.00"));
                                //最終必須接收一個double類型的數據
                                cell.setCellValue(doubleVal);
                            }
                            cell.setCellStyle(contentStyle);
                        }
                    }
                }
                sheet.setDefaultColumnStyle(0, getErrorColumnStyle(workbook));
            }
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下載文件,通用方法
     * @param response http響應體
     * @param fileName 下載文件名
     * @param consumer 下載過程回調
     */
    public static void download(HttpServletResponse response, String fileName, Consumer<OutputStream> consumer) {
        OutputStream out = null;
        try {
            String lowerFileName = fileName.toLowerCase();
            if (lowerFileName.endsWith(".png")) {
                response.setContentType("image/png");
            } else if (lowerFileName.endsWith(".jpg")) {
                response.setContentType("image/jpg");
            } else if (lowerFileName.endsWith(".jpeg")) {
                response.setContentType("image/jpeg");
            } else if (lowerFileName.endsWith(".gif")) {
                response.setContentType("image/gif");
            } else if (lowerFileName.endsWith(".bmp")) {
                response.setContentType("image/bmp");
            } else if (lowerFileName.endsWith(".pdf")) {
                response.setContentType("application/pdf");
            }
            else if (lowerFileName.endsWith(".xlsx")){
                System.out.println("xlsx");
                response.setContentType("application/vnd.ms-excel");
            } else if (lowerFileName.endsWith(".xls")){
                response.setContentType("application/vnd.ms-excel");
            }
            else {
                response.setContentType("application/octet-stream");
            }
            String encodeFileName = URLEncoder.encode(fileName, "utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + encodeFileName);
            out = response.getOutputStream();
            consumer.accept(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 內容單元格樣式
     * @param workbook
     * @return
     */
    private static CellStyle getContentStyle(Workbook workbook) {
        CellStyle contentStyel = workbook.createCellStyle();
        XSSFFont font = (XSSFFont) workbook.createFont();
        contentStyel.setFont(font);
        return contentStyel;
    }


    /**
     * 標題單元格樣式
     * @param workbook
     * @return
     */
    public static CellStyle getTitleStyle(Workbook workbook) {
        CellStyle titleStyel = workbook.createCellStyle();
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 設置粗體
        titleStyel.setFont(font);
        return titleStyel;
    }
    /**
     * 設置錯誤單元格樣式
     *
     * @Title: getErrorColumnStyle
     * @param workbook
     * @return
     * @return CellStyle
     * @throws
     */
    public static CellStyle getErrorColumnStyle(Workbook workbook) {
        CellStyle errorColumnStyel = workbook.createCellStyle();
        XSSFFont font = (XSSFFont) workbook.createFont();
//		font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 設置粗體
        font.setColor(Font.COLOR_RED);
        errorColumnStyel.setFont(font);
        errorColumnStyel.setFillBackgroundColor(XSSFFont.COLOR_RED);
        return errorColumnStyel;
    }

}

控制層

@RequestMapping(value = "/excel",method = RequestMethod.GET)
    public void exportExcel(HttpServletResponse response,Date startDate,Date endDate){
        try {
            List<Employee> employeesBetweenDate = employeeDao.getEmployeesBetweenDate(startDate,endDate);
            List<Map<String,Object>> resultMap = new ArrayList<Map<String,Object>>();
            employeesBetweenDate.forEach(employee->{
                Map<String,Object> ma = new HashMap<>();
                ma.put("員工id",employee.getEmployeeId());
                ma.put("員工姓名",employee.getEmployeeName());
                ma.put("員工生日",employee.getBirthday());
                resultMap.add(ma);
            });
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            List<String> titles = Arrays.asList("員工id", "員工姓名", "員工生日");
            ExportUtil.download(response,"員工信息表"+simpleDateFormat.format(new Date())+".xlsx",
                    o-> ExportUtil.exportExcel(titles,resultMap,o,"員工信息表"));
        } catch (Exception e) {
            LOGGER.error("導出員工信息表數據失敗" + e.getMessage(),e);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章