Facebook
From Scanty Sloth, 5 Days ago, written in Java.
Embed
Download Paste or View Raw
Hits: 27
  1. @Controller
  2. public class ExportController {
  3.  
  4.     @Autowired
  5.     private PanekVehicleRepository repository;
  6.     @Autowired
  7.     private CSVPanekWriter panekWriter;
  8.  
  9.     private static final Integer LIMIT = 750;
  10.  
  11.     @RequestMapping(value = "/export", method = RequestMethod.GET)
  12.     public String getExport(Model model) throws Exception {
  13.         model.addAttribute("period", new Period());
  14.         return "export";
  15.     }
  16.  
  17.     @RequestMapping(value = "/export", method = RequestMethod.POST, produces = "text/csv")
  18.     public String postExport(HttpServletResponse httpServletResponse,
  19.                              @ModelAttribute(value = "period") Period period) throws Exception {
  20.  
  21.         List<PanekVehicle> panekVehicleList = new ArrayList<>();
  22.         Long recordAmount = repository.countByPeriod(period.getDateFrom(), period.getDateTo());
  23.         int pageNr = 0;
  24.         while (pageNr*LIMIT < recordAmount) {
  25.             List<PanekVehicle> page = repository.findByPeriod(period.getDateFrom(), period.getDateTo(), new PageRequest(pageNr, LIMIT));
  26.             pageNr++;
  27.             panekVehicleList.addAll(page);
  28.         }
  29.  
  30.         CSVPrinter csvPrinter = panekWriter.transformResourcesToCSVPrinter(new BufferedWriter(httpServletResponse.getWriter()), panekVehicleList);
  31.         httpServletResponse.setContentType("application/csv");
  32.         httpServletResponse.setHeader("Content-Disposition", "attachment; filename="file.csv"");
  33.         csvPrinter.flush();
  34.         csvPrinter.close();
  35.         return "export";
  36.     }
  37.  
  38. }
  39.