poi導出excel工具類


poi版本

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


/**
 * Excel導出工具類
 * @author zsc
 * @datetime 2017年12月14日 下午8:01:32
 */
public class ExcelUtil {
	
	// 將需要的單元格式樣式放到Map集合中,使用時直接從Map中獲取,如果在使用時創建,那當數據量很大時嚴重影響性能
	public static ThreadLocal<Map<String, XSSFCellStyle>> styles = new ThreadLocal<>();
	
	/** 構造方法私有,禁止用戶new對象 */
	private ExcelUtil() {super();}
	
	/**
	 * 導出工作簿,將工作簿寫響應(response)輸出流實現瀏覽器下載
	 * @param response
	 * @param workbook
	 * @param fileName
	 * @throws Exception
	 */
	public static void exportExcel(HttpServletResponse response, XSSFWorkbook workbook, String fileName) throws Exception {
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
            response.setContentType("application/msexcel");
			workbook.write(os);
		} finally {
			if(null != workbook) {
				workbook.close();
			}
			if(null != os) {
				os.flush();
				os.close();
			}
		}
	}
	
	/**
	 * 創建工作簿
	 * @param sheetNames
	 * @param headNames
	 * @param titles
	 * @param contents
	 * @return
	 * @throws Exception
	 */
	public static XSSFWorkbook createExcel(String[] sheetNames, String[] headNames, 
			List<String[]> titles, List<List<Object[]>> contents) throws Exception {
		XSSFWorkbook workbook = new XSSFWorkbook();
		int sheetCount = sheetNames.length;
		XSSFSheet sheet = null;
		String headName = "";
		for(int i = 0; i < sheetCount; i++) {
			sheet = workbook.createSheet(sheetNames[i]);
			headName = (null != headNames && StringUtils.isNotBlank(headNames[i])) ? headNames[i] : sheetNames[i];
			createExcel(workbook, sheet, headName, titles.get(i), contents.get(i));
		}
		return workbook;
	}
	
	public static XSSFWorkbook createExcel(String sheetName, String headName, 
			String[] titles, List<Object[]> contents) throws Exception {
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet(sheetName);
		createExcel(workbook, sheet, headName, titles, contents);
		return workbook;
	}

	/**
	 * 創建工作簿
	 * @param workbook 導出工作簿
	 * @param sheet 導出工作表
	 * @param titles 標題列表
	 * @param contents 數據列表
	 * @throws Exception
	 */
	public static void createExcel(XSSFWorkbook workbook, XSSFSheet sheet, String[] titles, List<Object[]> contents) throws Exception {
		createExcel(workbook, sheet, sheet.getSheetName(), titles, contents);
	}
	
	/**
	 * 導出Excel
	 * @param os 輸出流
	 * @param workbook 導出工作簿
	 * @param sheet 導出工作表
	 * @param headName 表頭名
	 * @param titles 標題列表
	 * @param contents 數據列表
	 * @throws Exception
	 */
	public static void createExcel(XSSFWorkbook workbook, XSSFSheet sheet, String headName, 
			String[] titles, List<Object[]> contents) throws Exception {
		try {
			if(null == contents || contents.size() <= 0) {
				return;
			}
			// 創建單元格式樣式集合
			styles.set(styleMap(workbook));
			// 創建工作表頭
			createSheetHead(workbook, sheet, titles, headName);
			// 填充工作表數據
			createSheetData(sheet, contents, 2);
		} finally {
			if(null != styles.get()) {
				styles.get().clear();
			}
			styles.remove();
		}
	}
	
	/**
	 * 構建sheet表頭
	 * @param sheet
	 * @param heads
	 */
	private static void createSheetHead(XSSFWorkbook workbook, XSSFSheet sheet, String[] heads, String headName) {
		sheet.createFreezePane(0, 2, 0, 2);// 凍結前2行
		sheet.setDefaultColumnWidth((short) 20);// 設置表格默認列寬度爲20個字節
		XSSFCellStyle tilteStyle = styles.get().get("head");
		XSSFCell cell = null;
		XSSFRow rowFirst = sheet.createRow(0);// 創建第一行(報表名稱)
		cell = rowFirst.createCell(0);
		cell.setCellValue(StringUtils.isBlank(headName) ? sheet.getSheetName() : headName);
		cell.setCellStyle(tilteStyle);
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, heads.length -1));
		
		XSSFRow row = sheet.createRow(1);// 創建第二行(列名)
		if (heads != null && heads.length > 0) {
			XSSFCellStyle cellStyle = styles.get().get("title");
			for (int i = 0; i < heads.length; i++) {
				cell = row.createCell(i);
				if (heads[i] != null) {
					cell.setCellValue(heads[i]);
					cell.setCellStyle(cellStyle);
				}
			}
		}
	}
	
	/**
	 * 構建sheet數據內容
	 * @param sheet
	 * @param contents
	 * @param index
	 */
	private static void createSheetData(XSSFSheet sheet, List<Object[]> contents, int index) {
		XSSFCellStyle contentStyle = ExcelUtil.styles.get().get("content");
		XSSFCellStyle integerStyle = ExcelUtil.styles.get().get("integer");
		XSSFCellStyle doubleStyle = ExcelUtil.styles.get().get("double");
		Iterator<Object[]> it = contents.iterator();
		Row nextrow;
		Cell cell2;
		Object[] obj;
		// 遍歷數據
		while (it.hasNext()) {
			nextrow = sheet.createRow(index++);
			obj = it.next();
			if (obj != null) {
				int objLen = obj.length;
				for (int i = 0; i < objLen; i++) {
					cell2 = nextrow.createCell(i);
					if (obj[i] != null) {
						if(obj[i] instanceof Float || obj[i] instanceof Double || StringUtil.isNumeric1(obj[i].toString())){
							cell2.setCellValue(Double.parseDouble(obj[i].toString()));
							cell2.setCellStyle(doubleStyle);
						}else if(obj[i] instanceof Integer || (obj[i] instanceof Long && obj[i].toString().length() <=10)
								|| (StringUtil.isNumeric(obj[i].toString()) && obj[i].toString().length() <= 10)){
							cell2.setCellValue(Integer.parseInt(obj[i].toString()));
							cell2.setCellStyle(integerStyle);
						}else{
							cell2.setCellValue(obj[i].toString());
							cell2.setCellStyle(contentStyle);
						}
					} else {
						cell2.setCellValue("");
						cell2.setCellStyle(contentStyle);
					}
				}
			}
		}
	}
	
	/**
     * 創建單元格表頭樣式
     *
     * @param workbook 工作薄
     */
    private static XSSFCellStyle createCellHeadStyle(XSSFWorkbook workbook) {
    	XSSFCellStyle style = workbook.createCellStyle();
     // 設置邊框樣式
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        //設置對齊樣式
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成字體
        XSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 20);
        font.setBold(true);
        // 把字體應用到當前的樣式
        style.setFont(font);
        return style;
    }
    
    /**
     * 創建單元格表頭標題樣式
     *
     * @param workbook 工作薄
     */
    private static XSSFCellStyle createCellTitleStyle(XSSFWorkbook workbook) {
    	XSSFCellStyle style = workbook.createCellStyle();
     // 設置邊框樣式
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        //設置對齊樣式
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成字體
        XSSFFont font = workbook.createFont();
        // 表頭樣式
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(new XSSFColor(Color.CYAN));
        font.setBold(true);
        // 把字體應用到當前的樣式
        style.setFont(font);
        return style;
    }

    /**
     * 創建單元格正文樣式
     *
     * @param workbook 工作薄
     */
    private static XSSFCellStyle createCellContentStyle(XSSFWorkbook workbook) {
    	XSSFCellStyle style = workbook.createCellStyle();
        // 設置邊框樣式
        style.setBorderBottom(BorderStyle.THIN );
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        // 生成字體
        XSSFFont font = workbook.createFont();
        // 正文樣式
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        font.setBold(false);
        // 把字體應用到當前的樣式
        style.setFont(font);
        return style;
    }

    /**
     * 單元格樣式(Integer)列表
     */
    private static XSSFCellStyle createCellContent4IntegerStyle(XSSFWorkbook workbook) {
    	XSSFCellStyle style = workbook.createCellStyle();
        // 設置邊框樣式
        style.setBorderBottom(BorderStyle.THIN );
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        // 生成字體
        XSSFFont font = workbook.createFont();
        // 正文樣式
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        font.setBold(false);
        // 把字體應用到當前的樣式
        style.setFont(font);
        style.setDataFormat(workbook.createDataFormat().getFormat("#,##0"));//數據格式只顯示整數
        return style;
    }

    /**
     * 單元格樣式(Double)列表
     */
    private static XSSFCellStyle createCellContent4DoubleStyle(XSSFWorkbook workbook) {
    	XSSFCellStyle style = workbook.createCellStyle();
        // 設置邊框樣式
        style.setBorderBottom(BorderStyle.THIN );
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        // 生成字體
        XSSFFont font = workbook.createFont();
        // 正文樣式
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        font.setBold(false);
        // 把字體應用到當前的樣式
        style.setFont(font);
        style.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00"));//保留兩位小數點
        return style;
    }
	
	/**
     * 單元格樣式列表
     */
    private static Map<String, XSSFCellStyle> styleMap(XSSFWorkbook workbook) {
        Map<String, XSSFCellStyle> styleMap = new LinkedHashMap<>();
        styleMap.put("head", createCellHeadStyle(workbook));
        styleMap.put("title", createCellTitleStyle(workbook));
        styleMap.put("content", createCellContentStyle(workbook));
        styleMap.put("integer", createCellContent4IntegerStyle(workbook));
        styleMap.put("double", createCellContent4DoubleStyle(workbook));
        return styleMap;
    }
}

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