将java bean写入Csv表格式

时间:2017-01-07 02:11:53

标签: java csv export-to-csv opencsv

有没有办法使用Open Csv将Java bean写入Csv表格式? 有哪些其他库可以实现这一目标?

1 个答案:

答案 0 :(得分:0)

uniVocity-parsers支持与java bean之间的转换是无与伦比的。这是一个类的简单示例:

public class TestBean {

    // if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
    @NullString(nulls = {"?", "-"})
    // if a value resolves to null, it will be converted to the String "0".
    @Parsed(defaultNullRead = "0")
    private Integer quantity

    @Trim
    @LowerCase
    @Parsed(index = 4)
    private String comments;

    // you can also explicitly give the name of a column in the file.
    @Parsed(field = "amount")
    private BigDecimal value;

    @Trim
    @LowerCase
    // values "no", "n" and "null" will be converted to false; values "yes" and "y" will be converted to true
    @BooleanString(falseStrings = {"no", "n", "null"}, trueStrings = {"yes", "y"})
    @Parsed
    private Boolean pending;
}

现在,要将实例写入文件,请执行以下操作:

Collection<TestBean> beansToWrite = someMethodThatProducesTheObjectYouWant();
File output = new File("/path/to/output.csv");
new CsvRoutines().writeAll(beansToWrite, TestBean.class, output, Charset.forName("UTF-8"));

该库提供了许多配置选项和实现您想要的方法。如果您发现自己反复使用相同的注释,只需定义元注释即可。例如,对包含`字符的字段应用替换转换,而不是在每个字段中声明这一点:

@Parsed
@Replace(expression = "`", replacement = "")
public String fieldA;

@Parsed(field = "BB")
@Replace(expression = "`", replacement = "")
public String fieldB;

@Parsed(index = 4)
@Replace(expression = "`", replacement = "")
public String fieldC;

您可以创建这样的meta-annotatin:

@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Replace(expression = "`", replacement = "")
@Parsed
public @interface MyReplacement {

@Copy(to = Parsed.class)
String field() default "";

@Copy(to = Parsed.class, property = "index")
int myIndex() default -1;

并在你的班级中使用它:

@MyReplacement
public String fieldA;

@MyReplacement(field = "BB")
public String fieldB;

@MyReplacement(myIndex = 4)
public String fieldC;
}

我希望它有所帮助。

免责声明:我是这个库的作者,它是开源的,免费的(Apache V2.0许可证)