Ravi Kumar
Ravi Kumar

Reputation: 63

How to download csv file using spring boot controller with contents?

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?

Upvotes: 4

Views: 14974

Answers (3)

Udaya Kumar
Udaya Kumar

Reputation: 1

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.

Upvotes: 0

Li Daniel
Li Daniel

Reputation: 86

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

Upvotes: 4

PatrickChen
PatrickChen

Reputation: 1420

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

Upvotes: 3

Related Questions