getResult(@RequestParam String id) { final List getResult(@RequestParam String id) { final List getResult(@RequestParam String id) { final List

CSV generation taking longer with large data

63 Views Asked by At

Controller

@GetMapping(value = "/result", produces = "text/csv")
    public ResponseEntity<Resource> getResult(@RequestParam String id) {
    final List<Employee> empList = List.of(emp1, emp2);
        final InputStreamResource inputStreamResource = new InputStreamResource(validationResultsToCSV(empList));
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + "result.csv")
                .contentType(MediaType.parseMediaType("text/csv"))
                .body(inputStreamResource);
    }
    


    public ByteArrayInputStream validationResultsToCSV(final List<Employee> empList) {        
        final CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL);
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             final CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out), format)) {
            final List<String> header = new ArrayList<>();
            header.addAll(List.of("id", "emp name"));            
            csvPrinter.printRecord(header);            
                for (final Employee emp : entity.getCoverageStaging()) {
                    final List<String> data = new ArrayList<>();
                    data.addAll(Arrays.asList(emp.getId(), emp.getName()));                    
                    csvPrinter.printRecord(data);      
            }               
            csvPrinter.flush();            
            return new ByteArrayInputStream(out.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("Fail to import data to CSV file: " + e.getMessage());
        }
    }

This code is taking around 2-3 mins to generate csv for 50k records which seems long. is there any alternate and fast way to deal with this kind of case?

0

There are 0 best solutions below