1.pom文件添加如下
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
2.工具类代码
import com.csvreader.CsvWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Iterator;
/**
* @Author GaoYongQin
* @create 2019/4/28 14:17
*/
public class CsvUtils {
public static <T> void writeCSV(Collection<T> dataset, String csvFilePath, String[] csvHeaders) {
try {
// 定义路径,分隔符,编码
CsvWriter csvWriter = new CsvWriter(csvFilePath,'+', Charset.forName("UTF-8"));
// 写表头
csvWriter.writeRecord(csvHeaders);
// 写内容
//遍历集合
Iterator<T> it = dataset.iterator();
while (it.hasNext()) {
T t = (T) it.next();
//获取类属性
Field[] fields = t.getClass().getDeclaredFields();
String[] csvContent=new String[fields.length];
for (short i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
if (value == null) {
continue;
}
//取值并赋给数组
String textvalue=value.toString();
csvContent[i]=textvalue;
}catch (Exception e) {
e.getStackTrace();
}
}
//迭代插入记录
csvWriter.writeRecord(csvContent);
}
csvWriter.close();
System.out.println("<--------CSV文件写入成功-------->");
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.测试实体类
pom文件中引入
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
import lombok.Data;
/**
* @Author GaoYongQin
* @create 2019/4/30 15:09
*/
@Data
public class Student {
private int id;
private String name;
private int age;
}
4.主方法
public static void main(String[] args) {
List<Student> studentList = new ArrayList();
Student student = new Student();
student.setId(1);
student.setName("高哈哈");
student.setAge(18);
Student student1 = new Student();
student1.setId(2);
student1.setName("刘哈哈");
student1.setAge(17);
Student student2 = new Student();
student2.setId(3);
student2.setName("哇哈哈");
student2.setAge(14);
studentList.add(student);
studentList.add(student1);
studentList.add(student2);
String[] investHeaders = { "id", "姓名","年龄" };
String path = "D:/";
String fileName = "班级花名";
CsvUtils.writeCSV(studentList,path+fileName,investHeaders);
}