我在下载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文件,而不是将其保存到特定的位置。我正面临这个问题,如何解决?
2条答案
按热度按时间6g8kf2rb1#
这段代码可以得到一个简单的excel文件
7z5jn7bk2#