java 指定有序字段导出CSV文件的通用工具类

headerMaps为表头与类字段对应的有序map集

datas为list数据集

public class CSVUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(Thread
			.currentThread().getStackTrace()[1].getClassName());
	
	/**
	 * 导出CSV文件
	 * @param response 响应
	 * @param fileName 导出文件名
	 * @param headerMaps 表头与字段对应的有序集合
	 * @param datas 导出的数据
	 * @throws Exception
	 */
	public static <T> void exportCSV(HttpServletResponse response,
			String fileName, LinkedHashMap<String, String> headerMaps, List<T> datas) throws Exception {
		response.setHeader("Content-disposition", "attachment;filename="
				+ fileName + ".csv");
		response.setContentType("text/csv");
		response.setCharacterEncoding("UTF-8");
		String sep = ",";
		try {
			OutputStream out = response.getOutputStream();
			if (headerMaps == null || headerMaps.size() == 0 || datas == null || datas.size() == 0) {
				return;
			}
			// 检查字段是否符合要求
			Field[] fields = datas.get(0).getClass().getDeclaredFields();
			Map<String, String> checkMaps = checkFileds(fields, headerMaps);
			if (!checkMaps.get("code").equals("0")) {
				out.write(("字段检查异常," +  checkMaps.get("msg")).getBytes());
				throw new Exception("字段检查异常," +  checkMaps.get("msg"));
			}
			// 输出表头
			for (Iterator<String> i = headerMaps.keySet().iterator(); i.hasNext();) {
				String key = i.next();
				out.write(("\"" + key + "\"").getBytes());
				if (i.hasNext()) {
					out.write(sep.getBytes());
				} else {
					out.write("\r".getBytes());
				}
			}
			// 输出内容
			for (T data : datas) {
				Method[] methods = data.getClass().getDeclaredMethods();
				for (Iterator<String> i = headerMaps.keySet().iterator(); i.hasNext();) {
					String key = i.next();
					String fieldName = headerMaps.get(key);
					String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
					for (Method method : methods) {
						if (method.getName().equals(getMethodName)) {
							StringBuilder value = new StringBuilder();
							if (method.invoke(data, new Object[]{}) != null 
									&& method.invoke(data, new Object[]{}).toString().length() != 0) {
								value.append("\"").append(method.invoke(data, new Object[] {}).toString()).append("\"");
							} else {
								value.append("\"").append("\"");
							}
							out.write(value.toString().getBytes());
							if (i.hasNext()) {
								out.write(sep.getBytes());
							} else {
								out.write("\r".getBytes());
							}
						}
					}
				}
			}	
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error("CSV导出异常:" + e);
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 检查填写的字段是否符合要求
	 * @param fields 实体类字段
	 * @param headerMaps 表头与字段对应集合
	 * @return
	 */
	private static Map<String, String> checkFileds(Field[] fields, LinkedHashMap<String, String> headerMaps) {
		Map<String, String> checkMap = new HashMap<String, String>();
		checkMap.put("code", "0");
		for (Iterator<String> i = headerMaps.keySet().iterator(); i.hasNext();) {
			boolean result = false;
			String key = i.next();
			String value = headerMaps.get(key);
			for (Field field : fields) {
				if (field.getName().equals(value)) {
					result = true;
				}
			}
			if (!result) {
				checkMap.put("code", "1");
				checkMap.put("msg", "字段:" + value + "不存在!");
				return checkMap;
			}
		}
		return checkMap;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值