Java 如何使用带内容的spring boot controller下载csv文件?

Java 如何使用带内容的spring boot controller下载csv文件?,java,spring,spring-boot,rest,spring-mvc,Java,Spring,Spring Boot,Rest,Spring Mvc,我在下载csv文件时遇到了这个问题。我在SpringBoot中创建了GetAPI,并希望通过该api下载该文件。这是我的密码 @GetMapping(value = "/citydetails/download") public ResponseEntity<Object> getCityDetails() throws IOException { System.out.println("Starting the rest call."); FileWriter fi

我在下载csv文件时遇到了这个问题。我在SpringBoot中创建了GetAPI,并希望通过该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();
    }
}
@GetMapping(value=“/citydetails/download”)
公共响应属性getCityDetails()引发IOException{
System.out.println(“启动rest调用”);
FileWriter FileWriter=null;
服务=新的本地化服务();
试一试{
List details=service.getCityDetailsList();
if(details.isEmpty()){
System.out.println(“列表为空”);
}
StringBuilder fileContent=new StringBuilder(“州、区、市、村、PIN”);
对于(CityDetails数据:详细信息)
fileContent.append(data.getStatename()).append(data.getDistrict()).append(data.getCity())
.append(data.getVillage()).append(data.getPindode());
XSSFWorkbook工作簿=service.saveFileContents(详细信息);
String filename=“C:\\Users\\”+System.getProperty(“user.name”)+“\\Downloads\\cityDetails.csv”;
FileOutputStream out=新的FileOutputStream(文件名);
File File=新文件(“cityDetails.csv”);
练习册。写(出);
out=新文件输出流(文件);
返回ResponseEntity.ok()
.contentType(MediaType.parseMediaType(“text/csv”))
.header(HttpHeaders.CONTENT\u处置,“附件;文件名=\”+“cityDetails.csv”+“\”)
.机构(档案);
}捕获(例外情况除外){
System.out.println(“未能执行rest”+ex.getStackTrace()+“Locale:+ex.getLocalizedMessage());
ErrorDetails ErrorDetails=新的ErrorDetails(新日期(),例如getMessage(),“false”);
返回新的响应属性(errorDetails,HttpStatus.INTERNAL_SERVER_ERROR);
}最后{
if(filewriter!=null)
filewriter.close();
}
}
例外情况:

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

//image
@GetMapping(value=“/image”)
public@ResponseBody字节[]getImage()引发IOException{
InputStream in=getClass()
.getResourceAsStream(“/com/baeldung/produceimage/image.jpg”);
返回IOUtils.toByteArray(in);
}
//普通文件
@GetMapping(
value=“/get file”,
products=MediaType.APPLICATION\u OCTET\u STREAM\u值
)
public@ResponseBody byte[]getFile()引发IOException{
InputStream in=getClass()
.getResourceAsStream(“/com/baeldung/produceimage/data.txt”);
返回IOUtils.toByteArray(in);
}

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

有什么问题吗?你不知道如何返回响应?我想通过此api下载csv文件,我尝试了几种方法,但都失败了。最好列出代码或异常,有很多方法可以通过api下载文件,请检查此选项,我尝试过,但文件为空,没有内容。确保媒体类型正确,我发布了一些我的旧代码示例,您可以试试
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();