Create CSV with single column header in Java

11.6k Views Asked by At

How can I create CSV file in Java and set the header data in single columns instead of comma separated? For example:

Column A = Header1

Column B= Header2

Then write data below of each header:

Header1 Header2

Text1 Text2

Any example please? Many Thanks in advance.

2

There are 2 best solutions below

0
On

Use uniVocity-parsers to write CSV:

CsvWriterSettings settings = new CsvWriterSettings(); //many options here. Check the documentation

settings.getFormat().setDelimiter('|'); 

CsvWriter writer = new CsvWriter(new FileWriter(new File("path/to/output.csv")), settings);

writer.writeHeaders("Header A", "Header B");

//write rows individually
writer.writeRow("string 1", "string 2"); 
writer.writeRow(234, new BigDecimal(111)); 

//or write a list of rows in bulk
List<Object[]> yourRows = yourMethodToBuildRowsWithData();

writer.writeRowsAndClose(yourRows);

It seems you could use TSV instead of CSV to produce easier to visualise columns, separated by tab. In this case just replace the CsvWriterSettings and CsvWriter by TsvWriterSettings and TsvWriter

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

0
On

Finally I found the simple solution how to create CSV file and store the headers and values in separated columns. The example we need to have is:

ColumnA ColumnB
Value1  Value2

I didn’t use any library, using Java’s FileWriter I do the following. Change the comma delimiter from (,) to (;) as in example below.

private static final String COMMA_DELIMITER = ";";

Then define columns name and the rest example code.

private static final String FILE_HEADER = " **ColumnA; ColumnB**";
FileWriter fileWriter = null;
fileWriter = new FileWriter("your_csv_file.csv");
// Write the CSV file header
fileWriter.append(FILE_HEADER.toString());
// Add a new line separator after the header
fileWriter.append(NEW_LINE_SEPARATOR);
fileWriter.append(“Value1”);                
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(“Value2”);
fileWriter.append(NEW_LINE_SEPARATOR);
fileWriter.flush();
fileWriter.close();

Please note that you have to write the code correctly with try-catch and finally blocks.