How to Create a CSV File from a List Using Java and Spring Boot

Naveen Kumar Ravi
3 min readAug 1, 2023

--

Image by Markus Spiske from Pixabay

Introduction

In this tutorial, we will explore how to create a CSV file from a list of employee details using Java and Spring Boot. CSV (Comma-Separated Values) is a widely used format for storing tabular data. We’ll set up the development environment, define the folder structure, and follow best coding practices to generate the CSV file. This guide assumes you have basic knowledge of Java, Spring Boot, and how to set up a development environment.

Prerequisites:

  1. JDK 8 or higher installed on your machine.
  2. Spring Boot project setup with basic knowledge of RESTful APIs.
  3. A database with employee information. We’ll use a sample database with the Employee entity having attributes such as id, name, age, designation, and salary.

Step 1: Project Setup

  1. Create a new Spring Boot project using your preferred IDE or by using Spring Initializr (https://start.spring.io/). Include the necessary dependencies, such as Spring Web and Spring Data JPA.
  2. Set up the database connection in the application.properties file. Configure the datasource URL, username, and password for your database.

Step 2: Employee Entity

  1. Create an Employee class representing the entity in the database. Add attributes and corresponding getters and setters for id, name, age, designation, and salary.
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;
private int age;
private String designation;
private double salary;

// getters and setters
}

Step 3: Fetch Employee Data

  1. Create an EmployeeRepository interface by extending JpaRepository for querying employee data from the database.
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
// Add custom query methods if required
}

In your service or controller class, autowire the EmployeeRepository and use it to fetch all employees or a specific employee based on your requirements.

@RestController
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;

@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}

// Add other endpoints to fetch specific employees if needed
}

Step 4: Generating the CSV File

  1. Create a utility class to handle CSV file generation. Let’s call it CsvGeneratorUtil.
@Component
public class CsvGeneratorUtil {
private static final String CSV_HEADER = "ID,Name,Age,Designation,Salary\n";

public String generateCsv(List<Employee> employees) {
StringBuilder csvContent = new StringBuilder();
csvContent.append(CSV_HEADER);

for (Employee employee : employees) {
csvContent.append(employee.getId()).append(",")
.append(employee.getName()).append(",")
.append(employee.getAge()).append(",")
.append(employee.getDesignation()).append(",")
.append(employee.getSalary()).append("\n");
}

return csvContent.toString();
}
}

Step 5: Controller Endpoint to Generate CSV

  1. Create a new endpoint in the controller to trigger CSV generation and return the CSV content as a response.
@RestController
public class EmployeeController {
// ... (existing code)

@Autowired
private CsvGeneratorUtil csvGeneratorUtil;

@GetMapping("/employees/csv")
public ResponseEntity<byte[]> generateCsvFile() {
List<Employee> employees = employeeRepository.findAll();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "employees.csv");

byte[] csvBytes = csvGeneratorUtil.generateCsv(employees);

return new ResponseEntity<>(csvBytes, headers, HttpStatus.OK);
}
}
- src
- main
- java
- com
- yourcompany
- yourproject
- controller
- EmployeeController.java
- model
- Employee.java
- repository
- EmployeeRepository.java
- service
- CsvGeneratorUtil.java
- YourProjectApplication.java
- resources
- application.properties
- pom.xml

Conclusion:

Congratulations! You have successfully created a Spring Boot application that fetches employee data from the database and generates a CSV file containing employee details. By following the step-by-step instructions and utilizing advanced Java features, you’ve created a robust and efficient solution. Feel free to customize and expand this example to suit your specific needs or integrate it into your existing projects. Happy coding!

References:

  1. Spring Boot Documentation: https://spring.io/projects/spring-boot
  2. Spring Data JPA Documentation: https://spring.io/projects/spring-data-jpa
  3. JPA Annotations: https://www.baeldung.com/jpa-annotations
  4. Spring Boot with RESTful APIs: https://www.baeldung.com/spring-boot-restful-api-tutorial
  5. Spring Boot with CSV Files: https://www.baeldung.com/spring-boot-csv

These references provide in-depth explanations, examples, and best practices for Spring Boot and Java development. The Baeldung website (baeldung.com) offers comprehensive tutorials on various Java topics and is a valuable resource for developers. Feel free to explore these references to enhance your knowledge and skills in Spring Boot and Java development.

--

--

Naveen Kumar Ravi
Naveen Kumar Ravi

Written by Naveen Kumar Ravi

Technical Architect | Java Full stack Developer with 9+ years of hands-on experience designing, developing, and implementing applications.

Responses (1)