It looks like you are printing all the records on the same line .
Other methods like printRecords will be more helpful :
String outputFile = savePath+".csv";
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader();
FileWriter fileWriter = new FileWriter(outputFile);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecords(excelParser.getRecords());
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
Answer from Arnaud on Stack OverflowBaeldung
baeldung.com › home › java › java io › introduction to apache commons csv
Introduction to Apache Commons CSV | Baeldung
January 8, 2024 - Similarly, we can create a CSV file with the first line containing the headers: FileWriter out = new FileWriter("book_new.csv"); CSVPrinter printer = csvFormat.print(out); We presented the use of Apache’s Commons CSV library through a simple ...
Top answer 1 of 3
17
It looks like you are printing all the records on the same line .
Other methods like printRecords will be more helpful :
String outputFile = savePath+".csv";
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader();
FileWriter fileWriter = new FileWriter(outputFile);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecords(excelParser.getRecords());
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
2 of 3
11
Automatically close & flush
The Answer by Arnaud is correct and good. Here is a variation, shorter and more modern.
Here we:
- Use the
Path,File, andFilesclasses offered by modern Java NIO.2 to make easier work of file-handling. - Use a
BufferedWriterfor better performance with large amounts of data. - Specify the character encoding to be used. Usually UTF-8 is the best. If you do not understand, read this.
- Include the necessary try-catches for file-related exceptions.
- Add try-with-resources syntax to auto-close the file.
- Skip the explicit flushing, as the buffered writer will be flushed automatically as part of auto-closing the
BufferedWriterandCSVPrinter. To quote the Javadoc, callingjava.io.Writer::close“Closes the stream, flushing it first.”.
Code:
CSVFormat format = CSVFormat.EXCEL.withHeader();
Path path = Paths.get( savePath + ".csv" );
try
(
BufferedWriter writer = Files.newBufferedWriter( path , StandardCharsets.UTF_8 ) ;
CSVPrinter printer = new CSVPrinter( writer , format ) ;
)
{
printer.printRecords( excelParser.getRecords() );
}
catch ( IOException e )
{
e.printStackTrace();
}
// At this point, the `CSVPrinter` is automatically closed.
// And, ➡️ the `BufferedWriter` is automatically closed and flushed.
Apache Commons
commons.apache.org › proper › commons-csv › user-guide.html
User Guide – Apache Commons CSV
Apache Commons, Apache Commons CSV, Apache, the Apache logo, and the Apache Commons project logos are trademarks of The Apache Software Foundation.
Apache Commons
commons.apache.org › csv
Home – Apache Commons CSV
July 30, 2025 - Apache Commons, Apache Commons CSV, Apache, the Apache logo, and the Apache Commons project logos are trademarks of The Apache Software Foundation.
DZone
dzone.com › coding › java › working with csv files in java using apache commons csv
Working With CSV Files in Java Using Apache Commons CSV
April 30, 2018 - import java.io.IOException; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; public class BasicCsvWriter { public static void main(String[] args) { try { //We have to create the CSVPrinter class object Writer writer = Files.newBufferedWriter(Paths.get("student.csv")); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Student Name", "Fees")); //Writing records in the generated CSV file csvPrinter.printRecord("Akshay Sharma", 1000); csvPrinter.printRecord("Rahul Gupta", 2000); csvPrinter.printRecord("Jay Karn", 3000); //Writing records in the form of a list csvPrinter.printRecord(Arrays.asList("Dev Bhatia", 4000)); csvPrinter.flush(); } catch (IOException e) { e.printStackTrace(); } } }
GitHub
github.com › apache › commons-csv
GitHub - apache/commons-csv: Apache Commons CSV · GitHub
The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
Starred by 412 users
Forked by 304 users
Languages Java 99.8% | Shell 0.2%
Stack Abuse
stackabuse.com › reading-and-writing-csv-files-in-kotlin-with-apache-commons
Reading and Writing CSV Files in Kotlin with Apache Commons
February 27, 2023 - Similar to reading files, we can also write CSV files using Apache Commons. This time around, we'll be using the CSVPrinter. Just how the CSVReader accepts a BufferedReader, the CSVPrinter accepts a BufferedWriter, and the CSVFormat we'd like it to use while writing the file.
Medium
medium.com › @kaveeshapiumini1999 › data-export-using-apache-commons-csv-09a154243d97
Data Export using Apache Commons CSV | by Kaveeshapiumini | Medium
January 4, 2024 - Similarly, the library allows for writing data back to CSV files, enabling the generation of CSV files from Java data structures. Apache Commons CSV also handles various edge cases and exceptions that may arise when dealing with CSV files, such as handling special characters within fields and handling multi line records.
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › apache › commons › csv
Write/Read CSV Files with Apache Commons CSV Example - Java Code Geeks
November 9, 2023 - So, Let’s see how we can write and read a simple CSV file using the Apache Commons CSV. The latest stable release of Commons CSV is 1.0, we can download it from here or we can pull it from the central Maven repositories using the following dependency in your project POM: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.0</version> </dependency> We create this simple POJO to contain the student data like id, firstName, lastName, gender and age.
Stack Abuse
stackabuse.com › reading-and-writing-csvs-in-java-with-apache-commons-csv
Reading and Writing CSVs in Java with Apache Commons CSV
February 20, 2019 - The Apache Commons CSV library is the Apache Software Foundation's version of a Java CSV parser. According to the project summary, it attempts to "provide a simple interface for reading and writing CSV files of various types".
Top answer 1 of 2
4
How about this:
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(Header.class));) {
for (Map<Header, String> row : output) {
csvPrinter.printRecord(Arrays.asList(Header.values())
.stream()
.map(header -> row.get(header))
.collect(Collectors.toList()));
}
} catch (IOException ex) {
Logger.getLogger(TestCSV.class.getName())
.log(Level.SEVERE, null, ex);
}
2 of 2
1
Ok figured it out. I changed the maps to LinkedHashMap to retain order then did this:
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
.withHeader(Header.class));)
{
for (Map<Header, String> val : output)
{
csvPrinter.printRecord(val.values().toArray());
}
csvPrinter.flush();
} catch (IOException ex)
{
Logger.getLogger(TestCSV.class.getName()).log(Level.SEVERE, null, ex);
}