csv 文件是 

aaa,bbb,ccc

aaa,bbb,ccc

保存


这里的要求是 List<T> 线性表的类型 转换成 类别似 html 中 table的格式,即第一行是 head 后面是 body

使用注解的效果例如以下 :

List<User> users=new ArrayList<User>();
users.add(new User("刘夏楠", 23, "男"));
users.add(new User("刘夏楠", 23, "男"));
users.add(new User("刘夏楠", 23, "男"));

writeBeanToCsvFile("D:\\test.csv", users);


csv文件:

使用注解实现 bean 转 csv_html


当中bean user 例如以下:

package bean;

import annotation.csvField;

public class User {

@csvField("姓名") private String name;
@csvField("年龄")private Integer age;
private String sex;


public User(String name, Integer age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}


}



达到的效果就是

拥有 @csvField 注解的字段才会被 写入csv文件

而且 @csvField 的值作为csv文件的 title 即 第一行

我们使用反射来达到这个效果

bean 转 List<String[]> 例如以下:

private static <T> List<String[]> getStringArrayFromBean(List<T> beans) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
if(beans.size()<1)
throw new IllegalArgumentException("长度不能小于1");

List<String[]> result=new ArrayList<String[]>();
Class<? extends Object> cls=beans.get(0).getClass();//获取泛型类型
Field[] declaredFields=cls.getDeclaredFields();
List<Field> annoFields=new ArrayList<Field>();
for(int i=0;i<declaredFields.length;i++){//筛选出拥有注解的字段
csvField anno=declaredFields[i].getAnnotation(csvField.class);//获取注解
if(anno!=null)
annoFields.add(declaredFields[i]);
}
String[] title=new String[annoFields.size()];

for(int i=0;i<annoFields.size();i++){
title[i]=declaredFields[i].getAnnotation(csvField.class).value();//获取注解的值
}
result.add(title);

for(T each:beans){
String[] item=new String[annoFields.size()];
for(int i=0;i<annoFields.size();i++){
String fieldName=annoFields.get(i).getName();
String methodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);

Method method=each.getClass().getMethod(methodName, null);
String val=method.invoke(each, null).toString();
item[i]=val;
}
result.add(item);
}
return result;
}

然后使用 csv 的一个工具包 javacsv.jar来写入csv文件


public static <T> void  writeBeanToCsvFile(String csvFilePath,List<T> beans) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
File file =new File(csvFilePath);
if(!file.exists()){ //假设文件不存在,创建文件
file.createNewFile();
}
CsvWriter wr =new CsvWriter(csvFilePath,',', Charset.forName("GBK"));
List<String[]> contents=getStringArrayFromBean(beans);
for(String[] each:contents){
wr.writeRecord(each);
}
wr.close();
}

版权声明:本文博客原创文章,博客,未经同意,不得转载。