Created
November 13, 2017 03:37
-
-
Save pekrockstar/6994f3d07ccc8962a0e1373ddcd273da to your computer and use it in GitHub Desktop.
Export csv file by opencsv lib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.opencsv.CSVWriter; | |
import lombok.extern.slf4j.Slf4j; | |
import org.apache.commons.lang3.StringUtils; | |
import javax.servlet.http.HttpServletResponse; | |
import java.io.Writer; | |
import java.lang.reflect.Field; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import java.util.LinkedHashMap; | |
import java.util.List; | |
import java.util.Map; | |
@Slf4j | |
public class ExportCsvUtil { | |
private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); | |
public static <T> void export(String csvName, List<T> list, LinkedHashMap<String, String> fieldMap, | |
HttpServletResponse response) { | |
if (StringUtils.isBlank(csvName)) { | |
csvName = sdf.format(new Date()); | |
} else { | |
csvName = csvName + sdf.format(new Date()); | |
} | |
response.reset(); | |
response.setContentType("APPLICATION/OCTET-STREAM"); | |
response.setHeader("Content-disposition", "attachment; filename=" + csvName + ".csv"); | |
try (Writer writer = response.getWriter()) { | |
//BOM | |
writer.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF})); | |
CSVWriter cw = new CSVWriter(writer); | |
fillCsv(cw, list, fieldMap); | |
cw.flush(); | |
cw.close(); | |
} catch (Exception e) { | |
log.error(e.getMessage()); | |
} | |
} | |
private static Field getFieldByName(String fieldName, Class<?> clazz) { | |
Field[] selfFields = clazz.getDeclaredFields(); | |
for (Field field : selfFields) { | |
if (field.getName().equals(fieldName)) { | |
return field; | |
} | |
} | |
Class<?> superClazz = clazz.getSuperclass(); | |
if (superClazz != null && superClazz != Object.class) { | |
// Recursion | |
return getFieldByName(fieldName, superClazz); | |
} | |
return null; | |
} | |
private static Object getFieldValueByName(String fieldName, Object o) { | |
Object value = null; | |
Field field = getFieldByName(fieldName, o.getClass()); | |
if (field != null) { | |
try { | |
field.setAccessible(true); | |
value = field.get(o); | |
} catch (IllegalAccessException e) { | |
log.error(e.getMessage(), e); | |
} | |
} | |
return value; | |
} | |
/** | |
* Get "name" value or "department.name" value | |
* | |
* @param fieldNameSequence | |
* @param o | |
* @return | |
* @throws Exception | |
*/ | |
private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception { | |
Object value; | |
String[] attributes = fieldNameSequence.split("\\."); | |
if (attributes.length == 1) { | |
value = getFieldValueByName(fieldNameSequence, o); | |
} else { | |
Object fieldObj = getFieldValueByName(attributes[0], o); | |
String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1); | |
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj); | |
} | |
return value; | |
} | |
private static <T> void fillCsv(CSVWriter writer, List<T> list, LinkedHashMap<String, String> fieldMap) throws Exception { | |
String[] enFields = new String[fieldMap.size()]; | |
String[] cnFields = new String[fieldMap.size()]; | |
int count = 0; | |
for (Map.Entry<String, String> entry : fieldMap.entrySet()) { | |
enFields[count] = entry.getKey(); | |
cnFields[count] = entry.getValue(); | |
count++; | |
} | |
// Header | |
String[] headers = new String[count]; | |
for (int i = 0; i < cnFields.length; i++) { | |
headers[i] = cnFields[i]; | |
} | |
writer.writeNext(headers); | |
// content | |
String[] data = new String[count]; | |
for (int index = 0; index < list.size(); index++) { | |
T item = list.get(index); | |
for (int i = 0; i < enFields.length; i++) { | |
Object value = getFieldValueByNameSequence(enFields[i], item); | |
String str; | |
if (value == null) { | |
str = ""; | |
} else if (value instanceof Date) { | |
str = sdf.format(value); | |
} else { | |
str = String.valueOf(value); | |
} | |
data[i] = str; | |
} | |
writer.writeNext(data); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment