Import and export CSV files in a Spring Boot application

Category : Spring Boot | Sub Category : Spring Boot | By Prasad Bonam Last updated: 2023-07-09 09:39:15 Viewed : 365


Import and export CSV files in a Spring Boot application:

Here is an example of how to import and export CSV files in a Spring Boot application:

First, include the necessary dependencies in your pom.xml file:

xml
<!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Apache Commons CSV --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.9</version> </dependency>

Next, create a controller to handle the import and export operations:

java
import 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.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/api") public class CSVController { @PostMapping("/import") public ResponseEntity<String> importCSVFile(MultipartFile file) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { // Process each line of the CSV file // Perform your own logic here System.out.println(line); } return ResponseEntity.ok("CSV file imported successfully."); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.badRequest().body("Failed to import CSV file."); } } @RequestMapping(value = "/export", produces = "text/csv") public ResponseEntity<String> exportCSVFile() { try (StringWriter writer = new StringWriter(); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Name", "Age", "Email"))) { // Simulated data List<String> data1 = List.of("John Doe", "30", "john.doe@example.com"); List<String> data2 = List.of("Jane Smith", "25", "jane.smith@example.com"); // Add data rows to the CSV csvPrinter.printRecord(data1); csvPrinter.printRecord(data2); // Flush and close the CSV printer csvPrinter.flush(); csvPrinter.close(); // Prepare CSV file download response HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.csv"); return ResponseEntity.ok() .headers(headers) .body(writer.toString()); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.badRequest().body("Failed to export CSV file."); } } }

In the importCSVFile method, a MultipartFile parameter is used to receive the uploaded CSV file. The file is then read line by line, and you can process each line according to your specific logic.

In the exportCSVFile method, the CSVPrinter class is used to generate a CSV file with the specified data. In this example, simulated data is used, but you can replace it with your actual data. The generated CSV content is returned as a downloadable file with the appropriate response headers.

Finally, you can run your Spring Boot application and test the import and export endpoints using tools like cURL or Postman. For example, to import a CSV file, you can send a POST request with a multipart/form-data payload containing the CSV file. To export a CSV file, you can send a GET request to /api/export, and the CSV file will be downloaded.

Remember to customize the logic according to your specific use case, such as data processing, error handling, and validation.


Search
Sub-Categories
Related Articles

Leave a Comment: