有没有办法使用Open Csv将Java Bean写入Csv表格式?还有哪些其他库可用于实现此目的?
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;
您可以像这样创建一个元注释:
@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许可证)