使用POI導出Excel自適應列寬的實現


使用POI導出Excel時,涉及到如何自適應列寬的問題。方法如下

/**
	 * 下載excel文件,內容使用MAP存放
	 * 
	 * @param response
	 * @param headName
	 * @param tableHead
	 * @param tableBody
	 * @throws IOException
	 */
	public static void downloadExcelMap(HttpServletResponse response, String headName, List<String> tableHead,
			List<Map<Object, Object>> tableBody) throws IOException {
		headName=StringUtils.replaceAllSpecial(headName);
		// 1:創建一個workbook
		HSSFWorkbook workbook = new HSSFWorkbook();

		// 創建樣式
		HSSFCellStyle style = workbook.createCellStyle();
		Font font = workbook.createFont();
		font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 粗體
		style.setFont(font);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
		style.setBorderTop((short) 1);
		style.setBorderBottom((short) 1);
		style.setBorderLeft((short) 1);
		style.setBorderRight((short) 1);
		style.setWrapText(true);

		// 設置合計樣式
		HSSFCellStyle style1 = workbook.createCellStyle();
		style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
		style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
		style1.setBorderTop((short) 1);
		style1.setBorderBottom((short) 1);
		style1.setBorderLeft((short) 1);
		style1.setBorderRight((short) 1);
		style.setWrapText(true);

		HSSFSheet sheet = (HSSFSheet) workbook.createSheet(headName);
		// 2:合並單元格,表頭。並設置值
		CellRangeAddress cra = new CellRangeAddress(0, 0, 0, tableHead.size() - 1);
		sheet.addMergedRegion(cra);
		HSSFRow row = sheet.createRow(0);
		HSSFCell tableName = row.createCell(0);
		tableName.setCellStyle(style);
		tableName.setCellValue(headName);

		//存儲最大列寬
		Map<Integer,Integer> maxWidth = new HashMap<Integer,Integer>();
		
		// 3:設置表head
		HSSFRow row1 = sheet.createRow(1);
		for (int i = 0; i < tableHead.size(); i++) {
			Cell createCell = row1.createCell(i);
			createCell.setCellValue(tableHead.get(i));
			createCell.setCellStyle(style);
			maxWidth.put(i,createCell.getStringCellValue().getBytes().length  * 256 + 200);
		}
		// 4:表格內容
		for (int i = 0; i < tableBody.size(); i++) {
			HSSFRow rows = sheet.createRow(i + 2);
			int j = 0;
			for (Map.Entry<Object, Object> entry : tableBody.get(i).entrySet()) {
				HSSFCell createCell = rows.createCell(j);
				if(PropertyUtil.objectNotEmpty(entry.getValue())){
					createCell.setCellValue(entry.getValue().toString());
				}else{
					createCell.setCellValue("");
				}
				int length = createCell.getStringCellValue().getBytes().length  * 256 + 200;
		        //這里把寬度最大限制到15000
		        if (length>15000){
		            length = 15000;
		        }
				maxWidth.put(j,Math.max(length,maxWidth.get(j)));
				j++;
				createCell.setCellStyle(style1);
			}
		}
		
		// 列寬自適應
		for (int i = 0; i < tableHead.size(); i++) {
			sheet.setColumnWidth(i,maxWidth.get(i));
		}

		// 5:設置頭
		response.setHeader("Content-disposition",
				"attachment; filename=" + new String(headName.getBytes("GB2312"), "ISO8859-1") + ".xls");
		// 6:設置頭類型
		response.setContentType("application/vnd.ms-excel");
		
		// 7:寫出
		OutputStream toClient = response.getOutputStream();
		workbook.write(toClient);
		toClient.flush();
		toClient.close();

	}

 

注意:以上代碼有15000的限制,原因是Excel限制最大寬度為15000。所以,在這里我們除了這個寬度處理外,還需要設置單元格自動換行

style.setWrapText(true);

 

 簡書相關


免責聲明!

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



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