Is there any way to write Java bean to Csv table format using Open Csv ? What are the other libraries available to achieve this ?
Asked
Active
Viewed 919 times
1
-
http://stackoverflow.com/questions/30073980/java-writing-strings-to-a-csv-file http://opencsv.sourceforge.net/ – bakki Jan 07 '17 at 03:03
1 Answers
0
uniVocity-parsers support for conversions to and from java beans is unmatched. Here's a simple example of a class:
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;
}
Now, to write instances to a file, do this:
Collection<TestBean> beansToWrite = someMethodThatProducesTheObjectYouWant();
File output = new File("/path/to/output.csv");
new CsvRoutines().writeAll(beansToWrite, TestBean.class, output, Charset.forName("UTF-8"));
The library offers many configuration options and ways to achieve what you want. If you find yourself using the same annotations over and over again, just define a meta-annotation. For example, apply a replacement conversion over fields that contain the ` character, instead of declaring this in every single field:
@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;
You can create a meta-annotatin like this:
@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;
And use it in your class like this:
@MyReplacement
public String fieldA;
@MyReplacement(field = "BB")
public String fieldB;
@MyReplacement(myIndex = 4)
public String fieldC;
}
I hope it helps.
Disclaimer: I'm the author of this library, it's open-source and free (Apache V2.0 license)

Vishal Jamdade
- 182
- 1
- 2
- 17

Jeronimo Backes
- 6,141
- 2
- 25
- 29