【发布时间】:2017-05-21 21:20:59
【问题描述】:
有没有办法使用 Open Csv 将 Java bean 写入 Csv 表格式? 有哪些其他库可以实现这一目标?
【问题讨论】:
标签: java csv export-to-csv opencsv
有没有办法使用 Open Csv 将 Java bean 写入 Csv 表格式? 有哪些其他库可以实现这一目标?
【问题讨论】:
标签: java csv export-to-csv opencsv
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 许可)
【讨论】: