Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download csv using spring boot and apache commons

I have this below code for downloading CSV as an ajax button click, But the file is not downloading. Only showing the black new tab on the browser.

 @RequestMapping(value = "/batch/download", method = RequestMethod.POST, produces = "text/csv")
     @ResponseBody
     public void downloadNGIBatchSelected(HttpServletResponse response) throws IOException {
         List<String> ids = Arrays.asList("1312321","312313");

         generateNewCustomerCSV(response.getWriter(),ids);
     }

     private void generateNewCustomerCSV(PrintWriter writer, List<String> ids){
     String NEW_LINE_SEPARATOR = "\n";
       //CSV file header
       Object[] FILE_HEADER = {"Token Number",
               "Token Expiry Date",

          };
       CSVPrinter csvPrinter = null;
       try {
           csvPrinter = new CSVPrinter(new BufferedWriter(writer), CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));
           //Create CSV file header
           csvPrinter.printRecord(FILE_HEADER);

           for (PolicyMap PolicyMap : policyMaps) {
               List customerCSV = new ArrayList();
               customerCSV.add(PolicyMap.getInsurancePolicy().getTokenNo());
             try {
                   csvPrinter.printRecord(customerCSV);
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
               writer.flush();
               writer.close();
               csvPrinter.close();
           } catch (IOException e) {
               System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
               e.printStackTrace();
           }
       }
     }
like image 701
boycod3 Avatar asked Mar 03 '26 12:03

boycod3


1 Answers

You have set the content type in @RequestMapping annotation. But it is not going to work in the case when response is being written using HttpServletResponse. In this case, instead of spring, HttpServletResponse is writing the response that's why you have to set the response type in the response before getting the writer.

response.setContentType ("application/csv");
response.setHeader ("Content-Disposition", "attachment; filename=\"nishith.csv\"");
like image 156
Nisheeth Shah Avatar answered Mar 05 '26 22:03

Nisheeth Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!