1+ package root .utils ;
2+
3+ import java .lang .reflect .Field ;
4+ import java .util .Arrays ;
5+ import java .util .List ;
6+ import java .util .stream .Collectors ;
7+
8+ import org .apache .commons .lang3 .StringUtils ;
9+
10+ import com .opencsv .CSVWriter ;
11+
12+ public class CsvUtils {
13+
14+ /**
15+ *
16+ * @param list
17+ * @param clazz
18+ * @return
19+ */
20+ public static String toCsvString (List <?> list , Class <?> clazz ) {
21+ StringBuffer sb = new StringBuffer ();
22+
23+ try {
24+ Field [] fields = clazz .getDeclaredFields ();
25+ List <String > fieldName = Arrays .asList (fields ).stream ().map (f -> (f .getName ()))
26+ .collect (Collectors .toList ());
27+
28+ sb .append (createCsvHeader (fieldName ));
29+
30+ for (Object item : list ) {
31+ sb .append (CSVWriter .RFC4180_LINE_END ).append (createCsvRow (item , clazz ));
32+ }
33+ } catch (IllegalArgumentException | IllegalAccessException e ) {
34+ e .printStackTrace ();
35+ }
36+
37+ return sb .toString ();
38+ }
39+
40+ /**
41+ *
42+ * @param fieldNames
43+ * @return
44+ */
45+ public static String createCsvHeader (List <String > fieldNames ) {
46+ StringBuffer sb = new StringBuffer ();
47+
48+ for (String f : fieldNames ) {
49+ sb .append (sb .isEmpty () ? f : CSVWriter .DEFAULT_SEPARATOR + f );
50+ }
51+
52+ return sb .toString ();
53+ }
54+
55+ /**
56+ *
57+ * @param object
58+ * @param clazz
59+ * @return
60+ * @throws IllegalArgumentException
61+ * @throws IllegalAccessException
62+ */
63+ public static String createCsvRow (Object object , Class <?> clazz )
64+ throws IllegalArgumentException , IllegalAccessException {
65+ StringBuffer sb = new StringBuffer ();
66+
67+ if (StringUtils .equals (object .getClass ().getName (), clazz .getName ())) {
68+ for (Field f : clazz .getDeclaredFields ()) {
69+ boolean accessible = f .canAccess (object );
70+ f .setAccessible (true );
71+
72+ String appender = sb .isEmpty () ? StringUtils .getIfEmpty (f .get (object ).toString (), () -> "-" )
73+ : CSVWriter .DEFAULT_SEPARATOR + StringUtils .getIfEmpty (f .get (object ).toString (), () -> "-" );
74+ sb .append (appender );
75+
76+ f .setAccessible (accessible );
77+ }
78+ }
79+
80+ return sb .toString ();
81+ }
82+
83+ }
0 commit comments