Skip to content

6 Creating a document in memory

Dan Geabunea edited this page Apr 2, 2015 · 2 revisions

Reading existing CSV files is nice. But there are times when we would like to create documents in memory, and then to export them. EasyCSV allows the creation of CSV documents in memory.

Create a document programaticly

A CSV document is made up of rows. To build a document, we must first create the rows and then attach them to the document.

...
CsvRow firstRow= new CsvRow(new CsvColumn("John"), new CsvColumn(24), new CsvColumn(false));
CsvRow secondRow= new CsvRow(new CsvColumn("Anna"), new CsvColumn(30), new CsvColumn(true));
CsvDocument personsDocument = new CsvDocument(new ArrayList<>(Arrays.asList(firstRow,secondRow)));
...

The example above will produce a document like this:

John,24,false
Anna,30,true

Is there a less verbose way to create a CSV row?

Yes, you can pass the values directly to a CsvRow constructor, without the need to create explicit CsvColumns. The example bellow is equivalent to the previous one.

...
CsvRow firstRow = new CsvRow("John","24","false");
CsvRow secondRow= new CsvRow("Anna","30","true");
CsvDocument personsDocument = new CsvDocument(new ArrayList<>(Arrays.asList(firstRow,secondRow)));
...