4

I am facing the issue while downloading the csv file. I have created get api in spring boot and wanted to download the file through that api. Here is my code.

@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();
    }
}

Exception: enter image description here

Here i have used XSSFWorkbook to save my content to csv. Now i wanted to download the csv file through Rest api which will contain the data.I have tried multiple ways but i am getting empty file.With the above code it will save the csv file in download folder in windows machine, but i want this api to work on every system so I wanted to download the csv file with contents instead of saving it to specific location. I am facing the issue, how to resolve that?

5
  • What's the issue? you don't know how to return the response? Commented May 6, 2020 at 2:38
  • I want to download the csv file through this api, I have tried several ways but its failing. Commented May 6, 2020 at 2:45
  • better list the code or the exception, there are many ways you can download the file through API, check this stackoverflow.com/questions/35680932/… Commented May 6, 2020 at 2:48
  • I have tried but the file is empty, no content is present Commented May 6, 2020 at 2:58
  • make sure the media-type is correct, I post some my old code example, you could try Commented May 6, 2020 at 3:01

3 Answers 3

4
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();

This code can get a simple excel file

Sign up to request clarification or add additional context in comments.

Comments

3
//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);
}

Comments

0

To get the output or response in csv format we have to use open csv dependencies or apachepoicsv dependency. While we use HSSF (Horrible Spreadsheet Format) − It is used to read and write xls format of MS-Excel files.

XSSF (XML Spreadsheet Format) − It is used for xlsx file format of MS-Excel.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.