Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-07-09 09:42:32 Viewed : 643
Exporting and downloading a CSV file in Spring Boot:
Here is an example of exporting and downloading a CSV file in Spring Boot:
javaimport org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
@Controller
public class CSVController {
@GetMapping("/download")
public ResponseEntity<byte[]> downloadCSV() throws IOException {
List<String> headers = Arrays.asList("Name", "Age", "Email");
List<List<String>> data = Arrays.asList(
Arrays.asList("John Doe", "30", "john.doe@example.com"),
Arrays.asList("Jane Smith", "25", "jane.smith@example.com")
);
// Create CSV content
StringWriter writer = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(headers.toArray(new String[0])));
for (List<String> row : data) {
csvPrinter.printRecord(row);
}
csvPrinter.close();
byte[] csvBytes = writer.toString().getBytes();
// Prepare response with CSV content
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
headers.setContentDispositionFormData("attachment", "data.csv");
headers.setContentLength(csvBytes.length);
return new ResponseEntity<>(csvBytes, headers, HttpStatus.OK);
}
}
In this example, the /download
endpoint is used to export and download the CSV file. The CSV data, including headers and rows, is defined in the headers
and data
variables, respectively.
The CSVPrinter
class from Apache Commons CSV is used to generate the CSV content. It writes the CSV data into a StringWriter
, which is then converted into a byte array.
The ResponseEntity
class is used to construct the response. The CSV data is set as the response body, and appropriate headers, including the content type, content disposition, and content length, are set.
When you access the /download
endpoint in your browser or make a GET request to it, the CSV file will be downloaded with the name "data.csv".
Remember to adjust the CSV data and customize the logic according to your specific use case.