zoukankan      html  css  js  c++  java
  • java使用poi实现excel表格生成

     通过使用poi技术生成Excel,使用反射技术实现自动映射列表的数据。

    ExportTableUtil.java

    public class ExportTableUtil {
    
    	/**
    	 * 
    	 * @Description: 获取csv格式的字符串
    	 * @param @param 表格头
    	 * @param @param fieldNameList 对应的属性名 按照先后与表头对应而且值与数据类型的属性名对应
    	 * @param @param params 数据
    	 * @param @return
    	 * @param @throws IllegalArgumentException
    	 * @param @throws IllegalAccessException
    	 * @param @throws NoSuchFieldException
    	 * @param @throws SecurityException 设定文件
    	 * @return String 返回类型
    	 */
    	public static String csv(String[] headList, String[] fieldNameList, List<?> params) throws IllegalArgumentException, IllegalAccessException,
    			NoSuchFieldException, SecurityException {
    		StringBuilder stringBuilder = new StringBuilder();
    		// add head on first
    		for (int i = 0; null != headList && i < headList.length; i++) {
    			stringBuilder.append(headList[i]);
    			if (i < headList.length - 1) {
    				stringBuilder.append(",");
    			} else {
    				stringBuilder.append("
    ");
    			}
    		}
    		// add data from second line to ---
    		for (int i = 0; null != params && i < params.size(); i++) {
    			Class<? extends Object> clazz = params.get(i).getClass();
    			for (int j = 0; null != fieldNameList && j < fieldNameList.length; j++) {
    				String fieldName = fieldNameList[j];
    				if (!fieldName.contains(".")) {
    					Field field = clazz.getDeclaredField(fieldName);
    					if (null != field) {
    						field.setAccessible(true);
    						Object obj = field.get(params.get(i));
    						if (null != obj) {
    							stringBuilder.append(obj.toString());
    						}
    					} else {
    						stringBuilder.append("");
    					}
    					if (j < fieldNameList.length - 1) {
    						stringBuilder.append(",");
    					}
    				}else{
    					Object param = params.get(i);
    					Object valObj = vectorObj(clazz, fieldName, param);
    					if(null!=valObj){
    						stringBuilder.append(valObj.toString());
    					}else {
    						stringBuilder.append("");
    					}
    					if (j < fieldNameList.length - 1) {
    						stringBuilder.append(",");
    					}
    				}
    			}
    			stringBuilder.append("
    ");
    		}
    
    		return stringBuilder.toString();
    	}
    
    	/**
    	 * 
    	 * @Description: 通过response下载文档
    	 * @param @param response
    	 * @param @param fileName
    	 * @param @param headList
    	 * @param @param fieldNameList
    	 * @param @param params 设定文件
    	 * @return void 返回类型
    	 */
    	public static void httpExportCSV(HttpServletRequest request, HttpServletResponse response, String fileName, String[] headList,
    			String[] fieldNameList, List<?> params) {
    		Map<String, Object> map = new HashMap<String, Object>();
    		try {
    			response.setCharacterEncoding("UTF-8");
    			response.setContentType("application/x-download");
    			final String userAgent = request.getHeader("USER-AGENT");
    			String csvContent = csv(headList, fieldNameList, params);
    			String finalFileName = null;
    			if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
    				finalFileName = URLEncoder.encode(fileName, "UTF8");
    			} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
    				finalFileName = new String(fileName.getBytes(), "ISO8859-1");
    			} else {
    				finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
    			}
    
    			response.setHeader("Content-Disposition", "attachment; filename="" + finalFileName + """);
    			response.getOutputStream().write(csvContent.getBytes());
    		} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | IOException e) {
    
    			e.printStackTrace();
    			map.put("state", "202");
    			map.put("message", "数据转换异常");
    			try {
    				response.getOutputStream().write(JSONUtils.toJSONString(map).getBytes());
    			} catch (IOException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    		}
    
    	}
    
    	/**
    	 * 
    	 * @Description: 得到excel表的二进制流
    	 * @param @param headList 表头
    	 * @param @param fieldNameList 属性名按照表头先后顺序对应而且必须在数据类型中存在属性名与之对应
    	 * @param @param params
    	 * @param @return
    	 * @param @throws IllegalArgumentException
    	 * @param @throws IllegalAccessException
    	 * @param @throws NoSuchFieldException
    	 * @param @throws SecurityException
    	 * @param @throws IOException 设定文件
    	 * @return byte[] 返回类型
    	 */
    	public static byte[] xls(String[] headList, String[] fieldNameList, List<?> params) throws IllegalArgumentException, IllegalAccessException,
    			NoSuchFieldException, SecurityException, IOException {
    		Workbook work = new HSSFWorkbook();
    		Sheet sheet = work.createSheet();
    		Row rowOne = sheet.createRow(0);
    		for (int i = 0; null != headList && i < headList.length; i++) {// 表头
    			Cell cellOne = rowOne.createCell(i);
    			cellOne.setCellValue(headList[i]);// 填充值
    		}
    
    		// 数据填充
    		for (int i = 0; null != params && i < params.size(); i++) {
    			Class<? extends Object> clazz = params.get(i).getClass();
    			Row dataRow = sheet.createRow(i + 1);
    			for (int j = 0; null != fieldNameList && j < fieldNameList.length; j++) {
    				String fieldName = fieldNameList[j];
    				Cell cell = dataRow.createCell(j);
    				if (!fieldName.contains(".")) {
    					Field field = clazz.getDeclaredField(fieldName);
    					field.setAccessible(true);
    					Object obj = field.get(params.get(i));
    					if (null != obj) {
    
    						if (obj instanceof String) {
    							cell.setCellValue(obj.toString());
    						} else if (obj instanceof Double) {
    							cell.setCellValue((double) obj);
    						} else if (obj instanceof Boolean) {
    							cell.setCellValue((boolean) obj);
    						} else if (obj instanceof Date) {
    							cell.setCellValue((Date) obj);
    						} else {
    							cell.setCellValue(obj.toString());
    						}
    					}
    				} else if (fieldName.contains(".")) {
    					Object param = params.get(i);
    					Object valObj = vectorObj(clazz, fieldName, param);
    
    					cell.setCellValue(null == valObj ? null : valObj.toString());
    				}
    
    			}
    
    		}
    		ByteOutputStream bos = new ByteOutputStream();
    		work.write(bos);
    		work.close();
    		return bos.getBytes();
    	}
    
    	private static Object vectorObj(Class<? extends Object> clazz, String fieldName, Object obj) throws NoSuchFieldException, SecurityException,
    			IllegalArgumentException, IllegalAccessException {
    		if (!fieldName.contains(".")) {
    			Field field = clazz.getDeclaredField(fieldName);
    			field.setAccessible(true);
    			return field.get(obj);
    		} else {
    			String fieldChildName = fieldName.substring(0, fieldName.indexOf("."));
    			Object newObj = null;
    			if (null != fieldChildName) {
    
    				Field field = clazz.getDeclaredField(fieldChildName);
    				field.setAccessible(true);
    				newObj = field.get(obj);
    				if (newObj == null) {
    					return null;
    
    				} else {
    					Class<? extends Object> clazz2 = newObj.getClass();
    					String fieldOtherChildName = fieldName.substring(fieldName.indexOf(".") + 1);
    					return vectorObj(clazz2, fieldOtherChildName, newObj);
    				}
    
    			}
    			return null;
    		}
    
    	}
    
    	/**
    	 * 
    	 * @Description: 导出xls表-------------从第一列开始
    	 * @param @param request
    	 * @param @param response
    	 * @param @param fileName 文件名
    	 * @param @param headList 表头
    	 * @param @param fieldNameList 属性名 和按照表头先后顺序对应,值和数据列表中对象类型的属性名相同
    	 * @param @param params 设定文件
    	 * @return void 返回类型
    	 */
    	public static void httpExportXLS(HttpServletRequest request, HttpServletResponse response, String fileName, String[] headList,
    			String[] fieldNameList, List<?> params) {
    		Map<String, Object> map = new HashMap<String, Object>();
    		try {
    			response.setCharacterEncoding("UTF-8");
    			response.setContentType("application/x-download");
    			final String userAgent = request.getHeader("USER-AGENT");
    			byte[] xlsContent = xls(headList, fieldNameList, params);
    			String finalFileName = null;
    			if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
    				finalFileName = URLEncoder.encode(fileName, "UTF8");
    			} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
    				finalFileName = new String(fileName.getBytes(), "ISO8859-1");
    			} else {
    				finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
    			}
    
    			response.setHeader("Content-Disposition", "attachment; filename="" + finalFileName + """);
    			response.getOutputStream().write(xlsContent);
    		} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | IOException e) {
    
    			e.printStackTrace();
    			map.put("state", "202");
    			map.put("message", "数据转换异常");
    			try {
    				response.getOutputStream().write(JSONUtils.toJSONString(map).getBytes());
    			} catch (IOException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    		}
    	}
    
    	/**
    	 * 
    	 * @Description: 根据路径的后缀名导出对应的文件
    	 * @param @param request
    	 * @param @param response
    	 * @param @param fileName------------文件名(格式*.xls,*.csv)
    	 * @param @param headList--------------表格头部内容
    	 * @param @param fieldNameList----------属性名和数据列表中类型的属性名相同,通过先后循序和表头对应。
    	 * @param @param params--------------数据
    	 * @param @throws Exception ----文件名不合法
    	 * @return void 返回类型
    	 */
    	public static void httpExport(HttpServletRequest request, HttpServletResponse response, String fileName, String[] headList,
    			String[] fieldNameList, List<?> params) throws Exception {
    		if (null == fileName || StringUtils.isEmpty(fileName)) {
    			throw new NullPointerException("文件名不可以为空");
    		} else {
    			String suffix = fileName.substring(fileName.indexOf(".") + 1);
    			if (null != suffix) {
    				System.out.println(suffix);
    				switch (suffix) {
    				case "csv":
    					httpExportCSV(request, response, fileName, headList, fieldNameList, params);
    					break;
    				case "xls":
    					httpExportXLS(request, response, fileName, headList, fieldNameList, params);
    					break;
    				case "xlsx":
    					httpExportXLS(request, response, fileName, headList, fieldNameList, params);
    					break;
    				case "doc":
    					break;
    				case "docx":
    					break;
    				case "pdf":
    					break;
    				}
    			} else {
    				throw new Exception("文件名的格式不合法");
    			}
    		}
    	}
    }
    

      

  • 相关阅读:
    多线程--ThreadLocal类
    常用开发类库支持--UUID及空值处理Optional
    国际化的程序实现及其原理
    浅析java设计模式(一)----异构容器,可以存储任何对象类型为其他类提供该对象
    使用批处理命令注册运行mysql数据库,无需注册mysql服务,可以在任意电脑登录使用
    计算机中位、字长、字的区别
    SQL Server用户自定义数据类型
    简单的回合制小游戏
    单链表创建、删除、查找、插入之C语言实现
    LeetCode-905 Sort Array By Parity Solution (with Java)
  • 原文地址:https://www.cnblogs.com/maybo/p/5600199.html
Copyright © 2011-2022 走看看