Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Write Bean values to a CSV file using OpenCSV

 
Mike Anna
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using opencsv to read a CSV file and it works well.
I am currently trying to retrieve details from a database using hibernate and want to write the values to a csv file.

I saw they have examples where you can use the column mapping strategy and tie the indexes of the csv to a java bean but opencsv doesnt have anything like that for writing to csv files.
Lets say I get a)a list of Employee objects b)a list of Employee objects with Address (another class, included as a java.util.set in the employee pojo)embedded within
How could I go about writing a csv file in this scenaro ?

Cheers,
 
K. Tsang
Bartender
Posts: 3348
12
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a BeanToCsv class in the OpenCSV API. Well you already figured out how to read bean to csv like:


Then to write


I figured you wanted to write a list of list of beans then first how to produce a list of list of beans from reading then loop through it while writing.
 
Mike Anna
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your response. Sadly, I wasn't able to figure out a column mapping strategy while reading from csv.
How could one write directly from a bean, when it is a simple pojo and also when it has nested pojos within itself ?
 
Mike Anna
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
K. Tsang wrote:There's a BeanToCsv class in the OpenCSV API. Well you already figured out how to read bean to csv like:


Then to write


BTW, BeanToCsv is for ver 2.4 which isnt released yet.
I figured you wanted to write a list of list of beans then first how to produce a list of list of beans from reading then loop through it while writing.
 
K. Tsang
Bartender
Posts: 3348
12
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To produce list of list of beans List<List<YourBean>> is fairly simple if you got already got the original list.

Do the tradition stuff to populate the internal list as before.


Since BeanToCsv is not yet available I suggest you manually writing a class or function to does the same purpose using java.io package.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic