java中數據過多導出成多張Excel表格POI實現,直接上代碼了

首先將數據庫中獲取到的數據封成對象,生成一個工作簿,設定每張表的數據條數,循環生成多張表

@RequestMapping("/exportRegister")
	@ResponseBody
	public void downloadPerfect(RegisterVo r, HttpServletResponse response,HttpServletRequest request) {
		try {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//創建工作簿			
HSSFWorkbook wb = new HSSFWorkbook();
            //獲取用戶數據對象
			List<Register> AllList = registerService.getRegister(r);
            //將獲取到的數據對象分成60000條數據一個集合
			List<List<Register>> sprateList = ListUtils.partition(AllList,60000);
			int s=0;
			List<Map> mapList=null;
			Map<String,String> map = null;
			Register register;
            //遍歷集合,循環生成表
		    for(List<Register> oList : sprateList) {
		        mapList =new ArrayList<Map>();
				if(oList != null && oList.size() > 0) {
					for (int i = 0; i < oList.size(); i++) {
						map  = new HashMap<>();
						register = oList.get(i);
						if(register.getId()!=null) {map.put("num", register.getId().toString());}
						if(register.getTelephone()!=null) {map.put("phone", register.getTelephone());}
						if(register.getCid()!=null) {map.put("cyid", register.getCid());}
						if(register.getRegistertime()!=null) {map.put("register", formatter.format(register.getRegistertime()));}
						if(register.getIsapproveName()!=null) {map.put("isapproveName",register.getIsapproveName());}
						mapList.add(map);
					}
				}
				NewExcelExportUtil e = new NewExcelExportUtil();
				e.setTitle("");
				e.setHeardList(new String[] {"序號","手機號碼","創意ID","註冊時間","是否認證"});
				e.setHeardKey(new String[] {"num","phone","cyid","register","isapproveName"});
				e.setData(mapList);
				e.exportExport(wb,s);
				s++;
			}
            //生成工作簿導出
		    response.setHeader("Content-Disposition", "attachment;Filename=" + System.currentTimeMillis() + ".xlsx");
            OutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

將數據平分方法

 public static <T> List<List<T>> partition(final List<T> list, final int size) {
	        if (list == null) {
	            throw new NullPointerException("List must not be null");
	        }
	        if (size <= 0) {
	            throw new IllegalArgumentException("Size must be greater than 0");
	        }
	        return new Partition<>(list, size);
	    }
	    
	    private static class Partition<T> extends AbstractList<List<T>> {
	        private final List<T> list;
	        private final int size;

	        private Partition(final List<T> list, final int size) {
	            this.list = list;
	            this.size = size;
	        }

	        @Override
	        public List<T> get(final int index) {
	            final int listSize = size();
	            if (index < 0) {
	                throw new IndexOutOfBoundsException("Index " + index + " must not be negative");
	            }
	            if (index >= listSize) {
	                throw new IndexOutOfBoundsException("Index " + index + " must be less than size " +
	                                                    listSize);
	            }
	            final int start = index * size;
	            final int end = Math.min(start + size, list.size());
	            return list.subList(start, end);
	        }

	        @Override
	        public int size() {
	            return (int) Math.ceil((double) list.size() / (double) size);
	        }

	        @Override
	        public boolean isEmpty() {
	            return list.isEmpty();
	        }
	    }

生成工作表的方法

public class NewExcelExportUtil {
	
	//表頭
    private String title;
    //各個列的表頭
    private String[] heardList;
    //各個列的元素key值
    private String[] heardKey;
    //需要填充的數據信息
    private List<Map> data;
    //字體大小
    private int fontSize = 14;
    //行高
    private int rowHeight = 30;
    //列寬
    private int columWidth = 200;
    //工作表
    private String sheetName = "sheet1";

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String[] getHeardList() {
        return heardList;
    }

    public void setHeardList(String[] heardList) {
        this.heardList = heardList;
    }

    public String[] getHeardKey() {
        return heardKey;
    }

    public void setHeardKey(String[] heardKey) {
        this.heardKey = heardKey;
    }

    public List<Map> getData() {
        return data;
    }

    public void setData(List<Map> data) {
        this.data = data;
    }

    public int getFontSize() {
        return fontSize;
    }

    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
    }

    public int getRowHeight() {
        return rowHeight;
    }

    public void setRowHeight(int rowHeight) {
        this.rowHeight = rowHeight;
    }

    public int getColumWidth() {
        return columWidth;
    }

    public void setColumWidth(int columWidth) {
        this.columWidth = columWidth;
    }

    public String getSheetName() {
        return sheetName;
    }

    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }

    /**
     * 開始導出數據信息
     *
     */
    public byte[] exportExport(HSSFWorkbook wb,int s) throws IOException {
        //檢查參數配置信息
        checkConfig();
        //創建工作表
        HSSFSheet wbSheet = wb.createSheet(this.sheetName+s);
        //設置默認行寬
        wbSheet.setDefaultColumnWidth(20);

        // 標題樣式(加粗,垂直居中)
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        HSSFFont fontStyle = wb.createFont();
        fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        fontStyle.setBold(true);   //加粗
        fontStyle.setFontHeightInPoints((short)16);  //設置標題字體大小
        cellStyle.setFont(fontStyle);

        //在第0行創建rows  (表標題)
        HSSFRow title = wbSheet.createRow((int) 0);
        title.setHeightInPoints(30);//行高
        HSSFCell cellValue = title.createCell(0);
        cellValue.setCellValue(this.title);
        cellValue.setCellStyle(cellStyle);
        wbSheet.addMergedRegion(new CellRangeAddress(0,0,0,(this.heardList.length-1)));
        //設置表頭樣式,表頭居中
        HSSFCellStyle style = wb.createCellStyle();
        //設置單元格樣式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //設置字體
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) this.fontSize);
        style.setFont(font);
        //在第1行創建rows
        HSSFRow row = wbSheet.createRow((int) 1);
        //設置列頭元素
        HSSFCell cellHead = null;
        for (int i = 0; i < heardList.length; i++) {
            cellHead = row.createCell(i);
            cellHead.setCellValue(heardList[i]);
            cellHead.setCellStyle(style);
        }

        //設置每格數據的樣式 (字體紅色)
        HSSFCellStyle cellParamStyle = wb.createCellStyle();
        HSSFFont ParamFontStyle = wb.createFont();
        cellParamStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellParamStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        ParamFontStyle.setColor(HSSFColor.DARK_RED.index);   //設置字體顏色 (紅色)
        ParamFontStyle.setFontHeightInPoints((short) this.fontSize);
        cellParamStyle.setFont(ParamFontStyle);
        //設置每格數據的樣式2(字體藍色)
        HSSFCellStyle cellParamStyle2 = wb.createCellStyle();
        cellParamStyle2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellParamStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont ParamFontStyle2 = wb.createFont();
        ParamFontStyle2.setColor(HSSFColor.BLUE.index);   //設置字體顏色 (藍色)
        ParamFontStyle2.setFontHeightInPoints((short) this.fontSize);
        cellParamStyle2.setFont(ParamFontStyle2);
        //開始寫入實體數據信息
        int a = 2;
        for (int i = 0; i < data.size(); i++) {
            HSSFRow roww = wbSheet.createRow((int) a);
            Map map = data.get(i);
            HSSFCell cell = null;
            for (int j = 0; j < heardKey.length; j++) {
                cell = roww.createCell(j);
                cell.setCellStyle(style);
                Object valueObject = map.get(heardKey[j]);
                String value = null;
                if (valueObject == null) {
                    valueObject = "";
                }
                if (valueObject instanceof String) {
                    //取出的數據是字符串直接賦值
                    value = (String) map.get(heardKey[j]);
                } else if (valueObject instanceof Integer) {
                    //取出的數據是Integer
                    value = String.valueOf(((Integer) (valueObject)).floatValue());
                } else if (valueObject instanceof BigDecimal) {
                    //取出的數據是BigDecimal
                    value = String.valueOf(((BigDecimal) (valueObject)).floatValue());
                } else {
                    value = valueObject.toString();
                }
                //設置單個單元格的字體顏色
                if(heardKey[j].equals("ddNum") || heardKey[j].equals("sjNum")){
                if((Long)map.get("ddNum")!=null){
                    if((Long)map.get("sjNum")==null){
                        cell.setCellStyle(cellParamStyle);
                    } else if((Long) map.get("ddNum") != (Long) map.get("sjNum")){
                        if ((Long) map.get("ddNum") > (Long) map.get("sjNum")) {
                            cell.setCellStyle(cellParamStyle);
                        }
                        if ((Long) map.get("ddNum") < (Long) map.get("sjNum")) {
                            cell.setCellStyle(cellParamStyle2);
                        }
                    }else {
                        cell.setCellStyle(style);
                    }
                }
                }
                cell.setCellValue(Strings.isNullOrEmpty(value) ? "" : value);
            }
            a++;
        }

       return wb.getBytes();

    }

    /**
     * 檢查數據配置問題
     *
     * @throws IOException 拋出數據異常類
     */
    protected void checkConfig() throws IOException {
        if (heardKey == null || heardList.length == 0) {
            throw new IOException("列名數組不能爲空或者爲NULL");
        }

        if (fontSize < 0 || rowHeight < 0 || columWidth < 0) {
            throw new IOException("字體、寬度或者高度不能爲負值");
        }

        if (Strings.isNullOrEmpty(sheetName)) {
            throw new IOException("工作表表名不能爲NULL");
        }
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章