使用 spring boot 和 apache commons 下载 csv

boy*_*od3 3 apache-commons export-to-csv spring-boot

我有以下代码,用于将 CSV 下载为 ajax 按钮单击,但文件未下载。只在浏览器上显示黑色的新标签。

 @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();
           }
       }
     }
Run Code Online (Sandbox Code Playgroud)

Nis*_*hah 6

您已在@RequestMapping注释中设置了内容类型。但是在使用HttpServletResponse. 在这种情况下,而不是 springHttpServletResponse正在编写响应,这就是为什么您必须在获取编写器之前在响应中设置响应类型的原因。

response.setContentType ("application/csv");
response.setHeader ("Content-Disposition", "attachment; filename=\"nishith.csv\"");
Run Code Online (Sandbox Code Playgroud)

我希望它有效