Spring Boot + OpenCSV Export Data to CSV Example

Hello everyone, today we will learn how to export and download the data as a CSV file in a Spring Boot project. CSV stands for Comma-Separated-Values and it's a common format for doing a bulk data transfer between systems. For creating and parsing CSV files, we will use OpenCSV 3rd-party library.


A little bit of Background

Spring Boot

Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can "just run". 


OpenCSV

OpenCSV is an easy-to-use CSV (comma-separated values) parser library for Java. It was developed because all the CSV parsers at the time didn’t have commercial-friendly licenses. Java 8 is currently the minimum supported version. 


Technologies used 

  • Java 17
  • Spring Boot 2.7.0
  • OpenCSV 5.6
  • Spring Data JPA
  • H2DB
  • Maven



Project directory




Maven [pom.xml]

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details utilized by Maven to build the project. It contains default values for most projects. Some of the configurations that can be designated in the POM are the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists, and such can withal be designated.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath />
</parent>
<groupId>com.knf.dev</groupId>
<artifactId>springboot-opencsv</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-export-csv-demo</name>
<description>springboot-opencsv</description>

<properties>
<java.version>17</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.6</version>
</dependency>

</
dependencies>

<
build>
<
plugins>
<
plugin>
<
groupId>org.springframework.boot</groupId>
<
artifactId>spring-boot-maven-plugin</artifactId>
</
plugin>
</
plugins>
</
build>

</
project>



Create Employee Entity 

To be able to store user objects in the database using JPA we need to define an entity class. A JPA entity class is a POJO class, i.e. an ordinary Java class that is annotated as having the ability to represent objects in the database. 
package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String email;
private String country;
private String role;

public Employee() {
super();
}

public Employee(String name, String email,
String country, String role) {

this.name = name;
this.email = email;
this.country = country;

this.role = role;
}

public String getRole() {
return role;
}

public void setRole(String role) {
this.role = role;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}
}



Create Employee Repository

CrudRepository is a base interface and extends the Repository interface. CrudRepository mainly provides CRUD (Create, Read, Update, Delete) operations.
package com.example.demo.repository;

import org.springframework.data.repository.CrudRepository;
import com.example.demo.model.Employee;

public interface EmployeeRepository
extends CrudRepository<Employee, Long> {

}



Create Employee Service

The @Service annotation represents that our bean holds some business logic.
package com.example.demo.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;

@Service
public class EmployeeService {
@Autowired
EmployeeRepository employeeRepository;

public List<Employee> fetchAll() {

return (List<Employee>) employeeRepository.findAll();

}
}



Create Employee Controller

The @Controller annotation indicates that a particular class serves the role of a controller.
package com.example.demo.controller;

import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;

@Controller
public class EmployeeController {

@Autowired
EmployeeService employeeService;

@GetMapping("/export")
public void exportCSV(HttpServletResponse response)
throws Exception {

// set file name and content type
String filename = "Employee-List.csv";

response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");

// create a csv writer
StatefulBeanToCsv<Employee> writer =
new StatefulBeanToCsvBuilder<Employee>
(response.getWriter())
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withOrderedResults(false).build();

// write all employees to csv file
writer.write(employeeService.fetchAll());

}
}



Spring Boot Main Driver

The Spring Boot application's main class contains a public static void main() method that starts up the Spring ApplicationContext.
package com.example.demo;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;

@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
EmployeeRepository employeeRepository;

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
public void run(String... args) throws Exception {
List<Employee> employees = new ArrayList<>();

// creating dummy employees
employees
.add(new Employee("Alpha",
"alpha@ugmail.com",
"USA", "Architect"));
employees
.add(new Employee("Beta",
"beta@ugmail.com",
"India", "Manager"));
employees
.add(new Employee("Gama",
"gama@ugmail.com",
"Japan", "Developer"));
employees
.add(new Employee("Pekka",
"pekka@ugmail.com",
"India", "Analyst"));
employees
.add(new Employee("Tera",
"tera@ugmail.com",
"Romania", "Developer"));
employees
.add(new Employee("Byte",
"byte@ugmail.com",
"India", "Architect"));
employees
.add(new Employee("Danny",
"danny@ugmail.com",
"UK", "Architect"));
employees
.add(new Employee("Rahul",
"rahul@ugmail.com",
"India", "Developer"));
employees
.add(new Employee("Alpha",
"alpha@ugmail.com",
"USA", "QA"));
employees
.add(new Employee("June",
"june@ugmail.com",
"China", "Architect"));

employeeRepository.saveAll(employees);
}
}

Download the complete source code - click here                                        

Local Setup and Run the application

Step1: Download or clone the source code from GitHub to a local machine - Click here


Step 2: mvn clean install


Step 3: Run the Spring Boot application - mvn spring-boot:run

Hit this URL in your local system, http://localhost:8080/export

Open the file after download





More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example