3

Hi I have created a spring boot application to generate csv files that fetch data from database and write them into a csv file. Also I have added the functionality to select the columns that we need from the database to be included in the csv. Now I need to download multiple files with different columns from the database. I tried to repeat the code to generate csv in the same class but it simply adds the content required in the second file in the first file.Please let me know what can I do. Example if there are 4 columns:-id, amount, currency,name then id amount in 1 file name and currency in another.following is my code

Controller:

public void exportCSV(@RequestParam(name="cohort") String cohort ,HttpServletResponse response) throws Exception {
    
    // set file name and content type
    String filename = "liabilities.csv";
    response.setContentType("text/csv");
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, 
               "attachment; filename=\"" + filename + "\"");

    // Configure the CSV writer builder
    StatefulBeanToCsvBuilder<Report> builder = new StatefulBeanToCsvBuilder<Report>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(true);
   
    // Ignore any field except the `id` and `amount` ones
    Arrays.stream(Report.class.getDeclaredFields())
            .filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())))
            .forEach(field -> builder.withIgnoreField(Report.class, field));
    

    // create a csv writer
    StatefulBeanToCsv<Report> writer = builder.build();
    

    // write all employees to csv file
    writer.write(reportsService.findByCohort(cohort));
 }
}

The above code generates csv file with Id and amount entries from the database now what should i do to get currency and name in one csv and download it simultaneously.

0 Answers0