springmvc poi實現報表導出


1.pom文件:

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

2.controller 根據需要組裝數據:

private List<Map<String, Object>> createList(List<User> users){
        if(null == users) {
            return null;
        }
        String[] keys = {"name", "gender", "phoneNo", "email"};
        String[] excelHeader = {"姓名","性別", "手機號", "郵箱"};
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("fileName", "用戶表" + new Date().getTime());
        model.put("sheetName", "表一");
        model.put("title", "用戶表");
        model.put("keys", keys);
        model.put("excelHeader", excelHeader);
        list.add(model);
        
        for(User user : users) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", user.getName());
            map.put("gender", user.getGender());
            map.put("phoneNo", user.getPhoneNo());
            map.put("email", user.getEmail());
            list.add(map);
        }
        return list;
    }

 

3.ExcelUtil:

  

private static final Logger        LOG    = LoggerFactory.getLogger(ExcelUtil.class);

    /**創建一個excel文件*/
    private static Workbook createWorkBoot(String title,
            String[] excelHeader, List<Map<String, Object>> list, String[] keys) {
        Workbook workbook = new HSSFWorkbook();
        //設置sheet的名字
        Sheet sheet = workbook.createSheet(list.get(0).get("sheetName").toString());
        /*設置表格寬度*/
        for(int i = 0; i < keys.length; i++){
            sheet.setColumnWidth(i, 35*150);
        }

        /*font樣式設置字體大小,是否加粗*/
        Font titleFont = createFont(workbook, (short)20, true);
        Font headerFont = createFont(workbook, (short)12, true);
        Font bodyFont = createFont(workbook, (short)12, false);
        /*cell通用樣式*/
        CellStyle titleStyle = createStyle(workbook, titleFont);
        CellStyle headerStyle = createStyle(workbook, headerFont);
        CellStyle bodyStyle = createStyle(workbook, bodyFont);
        
        // excel中當前行索引
        int index = 0;
        /*合並標題的單元格設置標題信息及樣式 */
        sheet.addMergedRegion(new CellRangeAddress(index, index, index,
                excelHeader.length - 1));
        Row titleRow = sheet.createRow(index++);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(title);
        titleCell.setCellStyle(titleStyle);
        
        /*設置表格頭信息及樣式*/
        Row headerRow = sheet.createRow(index++);
        for(int i = 0; i < excelHeader.length; i++) {
            Cell headerCell = headerRow.createCell(i);
            headerCell.setCellValue(excelHeader[i]);
            headerCell.setCellStyle(headerStyle);
        }
        
        /*設置每行每 列的值及樣式
         *Row為行,cell為方格
         *創建i*j個方格並設置對應的屬性值*/
        for(int i = 1; i < list.size(); i++) {
            Row bodyRow = sheet.createRow(index++);
            for (int j = 0; j < keys.length; j++) {
                Cell bodyCell = bodyRow.createCell(j);
                bodyCell.setCellValue(list.get(i).get(keys[j]) == null ? 
                        " " : list.get(i).get(keys[j]).toString());
                bodyCell.setCellStyle(bodyStyle);
            }
        }
        return workbook;
    }
    
    /**設置字體大小,顏色,樣式,是否加粗*/
    private static Font createFont(Workbook workbook,
            short fontHeightInPoints, boolean isBlod) {
        Font font = workbook.createFont();
        //字體大小
        font.setFontHeightInPoints(fontHeightInPoints);
        //字體顏色
        font.setColor(IndexedColors.BLACK.getIndex());
        //字體樣式
        font.setFontName("宋體");
        //是否加粗
        font.setBold(isBlod);
        return font;
    }
    
    /**設置字體居中顯示,背景色,邊框*/
    private static CellStyle createStyle(Workbook workbook, Font font) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);
        //居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //背景顏色
        cellStyle.setFillForegroundColor(IndexedColors.WHITE.index);
        cellStyle.setFillBackgroundColor(IndexedColors.WHITE.index);
        cellStyle.setFillPattern(FillPatternType.FINE_DOTS);
        //邊框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        return cellStyle;
    }

    public static boolean exportExcel(HttpServletResponse response,List<Map<String, Object>> list) throws IOException {
        String fileName = list.get(0).get("fileName").toString();
        String[] excelHeader = (String [])list.get(0).get("excelHeader");
        String[] keys = (String [])list.get(0).get("keys");
        String title = list.get(0).get("title").toString();
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            createWorkBoot(title, excelHeader, list, keys).write(baos);
        } catch (IOException e) {
            LOG.error("將workbook中信息寫入輸出流時失敗");
            return false;
        }
        byte[] content = baos.toByteArray();
        InputStream is = new ByteArrayInputStream(content);

        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
            ServletOutputStream sos = response.getOutputStream();
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(sos);
            byte[] buff = new byte[2048];
            int byteRead = 0;
            while (-1 != (byteRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, byteRead);
            }
        } catch (IOException e) {
            LOG.error("創建excel文件時失敗");
            return false;
        } finally {
            if (bos != null)
                bos.close();
            if (bis != null)
                bis.close();
            if(is != null)
                is.close();
            if(baos != null)
                baos.close();
        }
        return true;
    }

導出效果

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM