how to store the result of a query in csv format, with java?

0

I have the following method in my controller, which retrieves form data and passes it as parameters to the service method to get the result of the query, what I need is to show the result of the query in a csv file and download it , but I do not know how, what library does it occupy? What do I need?

@RequestMapping(value= "/views/formulario", method = RequestMethod.POST)
public String obtieneDatos(@ModelAttribute("consultaForm") Factura fact, Model model) {
        
        String id = fact.getId();
        String cvePag=fact.getClavePago();
        Date fecha = fact.getFechaInicial();
        
 List<Factura> factList = obtieneInfoService.consultaDatos(id, cvePag, fecha);
        
       
}
    
asked by Root93 07.06.2018 в 05:06
source

1 answer

1

If it's only about generating CSV, the easiest thing is to do something like this:

class Factura {

    public String toCSVRepresentation() {
        StringBuilder builder = new StringBuilder();
        builder
            .add(getAttr1()).append(";")
            .add(getAttr2()).append(";")
            ....
            .add(getAttrN()).append(";");
        return builder.toString();
    }

And in your controller, after calling the service, you do this:

@RequestMapping(value= "/views/formulario", method = RequestMethod.POST, produces="text/csv")
public void obtieneDatos(@ModelAttribute("consultaForm") Factura fact, Model model, HttpServletResponse response) {
   String id = fact.getId();
   String cvePag=fact.getClavePago();
   Date fecha = fact.getFechaInicial();

   List<Factura> factList = obtieneInfoService.consultaDatos(id, cvePag, fecha);

   response.addHeader("Content-Type", "application/csv");
   response.addHeader("Content-Disposition", "attachment; filename=export.csv");
   try {
       PrintWriter out = response.getWriter();
       out.write("nombreCol1;nombreCol2;...;nombreColN;");
       out.write("\n");

       //Versión para Java 8
       //factList.forEach(result -> {
       //    out.write(result.toCSVRepresentation());
       //    out.write("\n");
       //});
       for(Factura result: factList) {
           out.write(result.toCSVRepresentation());
           out.write("\n");
       }

       out.flush();
       out.close();
   } catch (IOException ix) {
       throw new RuntimeException("There was an error while retrieving CSV data", ix);
   } 

}

If you already had to import CSVs, then you could use a library like Jackson Dataformat (com.fasterxml.jackson.dataformat: jackson-dataformat-csv) and you could use it for both processes.

    
answered by 07.06.2018 / 08:36
source