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.




Technologies used 

  • Spring Boot
  • OpenCSV
  • 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 is 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.1.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot_export_csv_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_export_csv_demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</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>4.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>


Employee Entity Class

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 int age;
private String role;

public Employee() {
super();
}

public Employee(String name, String email, String country,
int age, String role) {
super();

this.name = name;
this.email = email;
this.country = country;
this.age = age;
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;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}


DAO layer[EmployeeRepository.java]

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> {

}


Service layer[EmployeeService.java]

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();

}
}


EmployeeController.java

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-employees")
public void exportCSV(HttpServletResponse response)
throws Exception {

// set file name and content type
String filename = "employees.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 class

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 SpringbootExportCsvDemoApplication
implements CommandLineRunner {
@Autowired
EmployeeRepository employeeRepository;

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

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

// create dummy employees
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employeeRepository.saveAll(employees);
}
}


Run & Test

Local Setup:

Step 1: Download or clone the source code to a local machine.

Step 2mvn clean install

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

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



Open the downloaded CSV file



More related topics,

Java - Angular - VueJS - ReactJS

NodeJS - Angular - VueJS - ReactJS

Python - Flask  - Angular - VueJS - ReactJS

Popular posts from this blog

Spring boot video streaming example-HTML5

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring boot web project free download:User Registration System

Spring Boot + Mockito simple application with 100% code coverage

ReactJS - Bootstrap - Buttons

10 Best Job Posting Sites 2021-2022

Spring Boot + JPA/Hibernate One to Many mapping example

Spring Boot Export data to PDF example

Java - Blowfish Encryption and decryption Example