我在下载CSV文件时遇到了问题。 我在Spring 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 文件。我尝试了多种方法,但下载的文件都是空的。使用上述代码将会在 Windows 机器的下载文件夹中保存 csv 文件,但我希望这个 Api 在每台系统上都能正常工作,所以我想要直接下载包含内容的 csv 文件而不是保存到特定位置。我遇到了问题,请问如何解决?