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>


Model class[Employee.class]


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.class]


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.class]


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.class


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[SpringbootExportCsvDemoApplication.class]


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 

Run Spring Boot application with the command: mvn spring-boot:run

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




Open the downloaded CSV file



Download Source code

git clone: https://github.com/knowledgefactory4u/KnowledgeFactory.git

Comments

  1. You've provided quite good information here. This is fantastic since it expands our knowledge and is also beneficial to us. Thank you for sharing this piece of writing. Mexico Import Data

    ReplyDelete

Post a Comment