Spring MVC 如何下载csv文件使用 Spring Boot 控制器的内容?

2ledvvac  于 2022-11-14  发布在  Spring
关注(0)|答案(2)|浏览(194)

我在下载csv文件时遇到了这个问题。我在Sping Boot 中创建了get api,并希望通过该api下载文件。下面是我的代码。

@GetMapping(value = "/citydetails/download")
public ResponseEntity<Object> getCityDetails() throws IOException {
    System.out.println("Starting the rest call.");
    FileWriter filewriter = null;
    service = new LocalityService();
    try {
        List<CityDetails> details = service.getCityDetailsList();
        if (details.isEmpty()) {
            System.out.println("List is empty.");
        }
        StringBuilder fileContent = new StringBuilder("STATE,DISTRICT,CITY,VILLAGE,PIN\n");
        for (CityDetails data : details)
            fileContent.append(data.getStatename()).append(data.getDistrict()).append(data.getCity())
                    .append(data.getVillage()).append(data.getPindode());

        XSSFWorkbook workbook = service.saveFileContents(details);
        String filename = "C:\\Users\\" + System.getProperty("user.name") + "\\Downloads\\cityDetails.csv";
        FileOutputStream out = new FileOutputStream(filename);
        File file = new File("cityDetails.csv");
        workbook.write(out);
        out = new FileOutputStream(file);

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("text/csv"))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "cityDetails.csv" + "\"")
                .body(file);
    } catch (Exception ex) {
        System.out.println("Failed to execute rest" + ex.getStackTrace() + "Locale: " + ex.getLocalizedMessage());
        ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), "false");
        return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
    } finally {
        if (filewriter != null)
            filewriter.close();
    }
}

例外:

这里我已经使用XSSFWorkbook将我的内容保存到csv。现在我想通过Rest api下载csv文件,其中将包含数据。我已经尝试了多种方法,但我得到的是空文件。使用上面的代码,它将保存csv文件在windows机器的下载文件夹中,但是我希望这个API能在每个系统上工作,所以我想下载带有内容的csv文件,而不是将其保存到特定的位置。我正面临这个问题,如何解决?

6g8kf2rb

6g8kf2rb1#

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet=wkb.createSheet("sheet1");
HSSFRow row1=sheet.createRow(0);
HSSFCell cell=row1.createCell(0);
cell.setCellValue("table_demo");
sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));

//input Excel date
HSSFRow row2=sheet.createRow(1);    
row2.createCell(0).setCellValue("name");
row2.createCell(1).setCellValue("class");    
row2.createCell(2).setCellValue("score_1");
row2.createCell(3).setCellValue("score_2");    
HSSFRow row3=sheet.createRow(2);
row3.createCell(0).setCellValue("Jeams");
row3.createCell(1).setCellValue("High 3");
row3.createCell(2).setCellValue(87);    
row3.createCell(3).setCellValue(78);    

//output Excel file
OutputStream output=response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename=details.xls");
response.setContentType("application/msexcel");        
wkb.write(output);
output.close();

这段代码可以得到一个简单的excel文件

7z5jn7bk

7z5jn7bk2#

//image
@GetMapping(value = "/image")
public @ResponseBody byte[] getImage() throws IOException {
    InputStream in = getClass()
      .getResourceAsStream("/com/baeldung/produceimage/image.jpg");
    return IOUtils.toByteArray(in);
}

//normal file
@GetMapping(
  value = "/get-file",
  produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
)
public @ResponseBody byte[] getFile() throws IOException {
    InputStream in = getClass()
      .getResourceAsStream("/com/baeldung/produceimage/data.txt");
    return IOUtils.toByteArray(in);
}

相关问题