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;
}
}