1. 程式人生 > >【原創】POI 生成Excel文件並下載

【原創】POI 生成Excel文件並下載

pri posit 實現類 row itl utf-8 技術 require servle

ι 版權聲明:本文為博主原創文章,未經博主允許不得轉載。

效果圖:

技術分享圖片

實現

1.在pom中添加依賴:

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.17</version>
    </dependency
>

2.ExcelUtil工具類:

package com.feicuiedu.survey.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; import java.util.Map; /** * Created by Bella on 2018/2/5. */ public class ExcelUtil { /** * 創建excel文檔, * list 數據 * @param keys list中map的key數組集合 * @param
columnNames excel的列名 * */ public static HSSFWorkbook createWorkBook(List<Map<String, Object>> list, String []keys, String columnNames[]) { // 創建excel工作簿 HSSFWorkbook wb = new HSSFWorkbook(); // 創建第一個sheet頁,並命名 HSSFSheet sheet = wb.createSheet(list.get(0).get("sheetName").toString()); // 設置列寬 for(int i=0;i<keys.length;i++){ //最後一列為附件URL地址,列寬設置大一些 if(i==(keys.length-1)){ sheet.setColumnWidth((short) i, (short) (200*120)); }else{ sheet.setColumnWidth((short) i, (short) (50*60)); } } // 創建第一行,並設置其單元格格式 HSSFRow row = sheet.createRow((short) 0); row.setHeight((short)500); // 單元格格式(用於列名) HSSFCellStyle cs = wb.createCellStyle(); HSSFFont f = wb.createFont(); f.setFontName("宋體"); f.setFontHeightInPoints((short) 10); f.setBold(true); cs.setFont(f); cs.setAlignment(HorizontalAlignment.CENTER);// 水平居中 cs.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中 cs.setLocked(true); cs.setWrapText(true);//自動換行 //設置列名 for(int i=0;i<columnNames.length;i++){ HSSFCell cell = row.createCell(i); cell.setCellValue(columnNames[i]); cell.setCellStyle(cs); } //設置首行外,每行每列的值(Row和Cell都從0開始) for (short i = 1; i < list.size(); i++) { HSSFRow row1 = sheet.createRow((short) i); String flag = ""; //在Row行創建單元格 for(short j=0;j<keys.length;j++){ HSSFCell cell = row1.createCell(j); cell.setCellValue(list.get(i).get(keys[j]) == null?" ": list.get(i).get(keys[j]).toString()); if(list.get(i).get(keys[j])!=null){ if("優".equals(list.get(i).get(keys[j]).toString())){ flag = "優"; }else if("差".equals(list.get(i).get(keys[j]).toString())) { flag = "差"; } } } //設置該行樣式 HSSFFont f2 = wb.createFont(); f2.setFontName("宋體"); f2.setFontHeightInPoints((short) 10); if("優".equals(flag)){ HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setFont(f2); cellStyle.setAlignment(HorizontalAlignment.CENTER);// 左右居中 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中 cellStyle.setLocked(true); cellStyle.setWrapText(true);//自動換行 cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex());// 設置背景色 cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); //依次為每個單元格設置樣式 for(int m=0;m<keys.length;m++){ HSSFCell hssfCell = row1.getCell(m); hssfCell.setCellStyle(cellStyle); } }else if("差".equals(flag)){ HSSFCellStyle cellStyle2 = wb.createCellStyle(); cellStyle2.setFont(f2); cellStyle2.setAlignment(HorizontalAlignment.CENTER);// 左右居中 cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中 cellStyle2.setLocked(true); cellStyle2.setWrapText(true);//自動換行 cellStyle2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.RED.getIndex());// 設置背景色 cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND); for(int m=0;m<keys.length;m++){ HSSFCell hssfCell = row1.getCell(m); hssfCell.setCellStyle(cellStyle2); } }else{ HSSFCellStyle cs2 = wb.createCellStyle(); cs2.setFont(f2); cs2.setAlignment(HorizontalAlignment.CENTER);// 左右居中 cs2.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中 cs2.setLocked(true); cs2.setWrapText(true);//自動換行 for(int m=0;m<keys.length;m++){ HSSFCell hssfCell = row1.getCell(m); hssfCell.setCellStyle(cs2); } } } return wb; } //生成並下載Excel public static void downloadWorkBook(List<Map<String,Object>> list, String keys[], String columnNames[], String fileName, HttpServletResponse response) throws IOException{ ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ExcelUtil.createWorkBook(list,keys,columnNames).write(os); } catch (IOException e) { e.printStackTrace(); } byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 設置response參數 response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = response.getOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (final IOException e) { throw e; } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } }

3.service 接口:

    String export(HttpServletResponse response,
                         Integer regionid,
                         Integer schoolid,
                         Integer majorid,
                         String beginDate,
                         String endDate);

4.service 接口實現類:

    /**
     * 導出Excel表
     * @param regionid 大區id
     * @param schoolid 校區id
     * @param majorid 專業id
     * @param beginDate 開始日期
     * @param endDate 結束日期
     * @return
     */
    public String export(HttpServletResponse response,
                         Integer regionid,
                         Integer schoolid,
                         Integer majorid,
                         String beginDate,
                         String endDate){
        try {
            List<ProjectAuditListVo> projectAuditListVoList = projectAuditMapper.query(0,regionid,schoolid,majorid,null,beginDate,endDate,null,null);
            String fileName="項目審核表";
            List<Map<String,Object>> list=createExcelRecord(projectAuditListVoList);
            String columnNames[] = {"大區","校區","專業","面授教師","在線教師","班級",
                    "項目所處階段","作品人次","項目提交日期","項目得分",
                    "得分等級","原因","項目評價","附件"};//列名
            String keys[] = {"regionName","schoolName","majorName","teacherName","onlineTeacherName",
                    "className","stage","workNum", "submitTime","score","rank","reason","evaluate","attachment",};//map中的key
            ExcelUtil.downloadWorkBook(list,keys,columnNames,fileName,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "excel";
    }

    /**
     * 創建Excel表中的記錄
     * @param projectAuditListVoList
     * @return
     */
    private List<Map<String, Object>> createExcelRecord(List<ProjectAuditListVo> projectAuditListVoList){
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sheetName", "sheet1");
            listmap.add(map);
            for (int j = 0; j < projectAuditListVoList.size(); j++) {
                ProjectAuditListVo projectAuditListVo=projectAuditListVoList.get(j);
                Map<String, Object> mapValue = new HashMap<String, Object>();
                mapValue.put("regionName",projectAuditListVo.getRegionName());
                mapValue.put("schoolName",projectAuditListVo.getSchoolName());
                mapValue.put("majorName",projectAuditListVo.getMajorName());
                mapValue.put("teacherName",projectAuditListVo.getTeacherName());
                mapValue.put("onlineTeacherName",projectAuditListVo.getOnlineTeacherName());
                mapValue.put("className",projectAuditListVo.getClassName());
                mapValue.put("stage",projectAuditListVo.getStage());
                mapValue.put("workNum",projectAuditListVo.getWorkNum());
                mapValue.put("submitTime", DateTimeUtil.dateToStr(projectAuditListVo.getSubmitTime(),"yyyy-MM-dd"));
                mapValue.put("score",projectAuditListVo.getScore());
                mapValue.put("rank",projectAuditListVo.getRank());
                mapValue.put("reason",projectAuditListVo.getReason());
                mapValue.put("evaluate",projectAuditListVo.getEvaluate());
                String attachmentURL = projectAuditListVo.getAttachment()==null?"無":FileUtil.getUploadPath()+projectAuditListVo.getAttachment();
                mapValue.put("attachment",attachmentURL);
                listmap.add(mapValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listmap;
    }

其中,

List<ProjectAuditListVo> projectAuditListVoList = projectAuditMapper.query(0,regionid,schoolid,majorid,null,beginDate,endDate,null,null);

為調用dao 層方法,獲取 Excel中數據源。此處,dao層方法省略

5.controller層:

    @RequestMapping(value = "/export",produces = {"application/vnd.ms-excel;charset=UTF-8"})
    @ResponseBody
    public String export(HttpServletResponse response,
                         @RequestParam(value = "regionid",required = false) Integer regionid,
                         @RequestParam(value = "schoolid",required = false) Integer schoolid,
                         @RequestParam(value = "majorid",required = false) Integer majorid,
                         @RequestParam(value = "beginDate",required = false) String beginDate,
                         @RequestParam(value = "endDate",required = false) String endDate){

        return iProjectAuditService.export(response,regionid,schoolid,majorid,beginDate,endDate);
    }

6.訪問export接口,則會自動下載生成的Excel文件至本地。Excel文件效果圖如上圖所示。

【原創】POI 生成Excel文件並下載