Search code examples
javaexport-to-csv

Write ResultList from DB into a CSV file in Java


I need to write my query.getResultList() into a .CSV file.

I call the query over this:

    final Query q = em.createNamedQuery("getalljobs");
    final List<Job> joblist = q.getResultList();

and the Namequery just do SELECT * FROM TABLE, the result of query.getResultList() looks like this:

[id;name, id;name, ... ]

I can't use OpenCSV.

The CSV file needs to have headers.


Solution

  • You can use something like

    Query q = em.createNamedQuery("getalljobs");
    List<Job> jobList = q.getResultList();
    String csvHeader = getHeader();
    
    try (PrintWriter fw = new PrintWriter(new FileWriter("output.csv"))) {
      fw.println(csvHeader);
      for(String line : jobList){
        fw.println(line);
      }
    }